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