Home > Enterprise >  For loop not iterating in the function- Language: Python
For loop not iterating in the function- Language: Python

Time:09-09

I am new in learning coding and started with python. I trying to define a function which will iterate over each item in the list and return the item. However, the code is only returning the first item.

ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']

def second_char(y): for char in y: return char ky= second_char(ex_lst) print(ky)

Highly appreciate your input. Thanks.

CodePudding user response:

What you are doing is simply returning the first element of the list, Why? Because as soon as the compiler reaches the return statement it simply returns the value.

In your case

def second_char(y):
    for char in y:
    return char

As you can observe from this, the loop is going to call the return statement in its first iteration which will eventually return 1st element.

To make it right you've to make another list and append all the elements of ex_list into list and then return that.

ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']

def second_char(y):
    list = [] //creating a local list
    for x in y:
     list.append(x)  // storing the ex_list in list and returning it 
    return list
ky= second_char(ex_lst)
print(ky)
  • Related