I am trying to identify the first element, last element, and other elements in a python list using a function. If it’s the first element, I want 0 to be returned, if it’s the last element I want -1 to be returned, every other element should return 2.
I can achieve this without using a function but when I use a function, I don’t get the desired result. Please help me with this. Thanks in advance
What I have so far can be seen in the codes and screenshots below here is the code without using a function
a= [1,2,3,4,5,6]
for i, x in enumerate(a):
if i==0:
number=0
elif i==len(a)-1:
number=-1
else:
number=2
print (number)
here is the desired output, it is gotten when function is not used
here is the same code in a function
def cs():
a= [1,2,3,4,5,6]
for i, x in enumerate(a):
if i==0:
number=0
elif i==len(a)-1:
number=-1
else:
number=2
print (number)
return (number)
cs()
here is the output of the function. it returns only one index instead of six
If i try having the print/return statement outside the for loop, only the last element returns a value.
def cs():
a= [1,2,3,4,5,6]
for i, x in enumerate(a):
if i==0:
number=0
elif i==len(a)-1:
number=-1
else:
number=2
print (number)
return (number)
cs()
here is the output of the function with the print/return statement outside the for loop
CodePudding user response:
Your query- is it possible to iterate through the whole list and still use a return statement?
Instead of return
we use yield
to go through whole list.
def generator():
a= [1,2,3,4,5,6]
for i,x in enumerate(a):
if i==0:
yield 0
elif i==len(a)-1:
yield -1
else:
yield 2
gen_object = generator()
print(type(gen_object))
for i in gen_object:
print(i)
Output:-
<class 'generator'>
0
2
2
2
2
-1