Beginner question: I am trying to iterate over the lists and return each item to send to another list. I can only get it to return the last item in each list- 4 & 'home'. What am I doing wrong?
def held():
alist = [1, 2, 3, 4]
blist = ['bob', 'is','not', 'home']
for event in range(0,3):
for item in alist:
ide = item
acc_id = int(ide)
for item in blist:
sev = item
sever = str(sev)
return acc_id, sever
held()
CodePudding user response:
The return
statement can only get executed once in a method. It will only return the last elements because, the program will at first loop through the list and then return the values (that will then equals the last value of the list while that was the las iteration executed).
If you want to return something like [1, "bob", 2, "is"...]
, you could do something like :
array1 = [1, 3, 5]
array2= [2, 4, 6]
array3 = []
for index in range(0, len(array1)):
array3.append(array1[index])
array3.append(array2[index])
print(array3)
# Expexted output : [1, 2, 3, 4, 5, 6]
As said in the comments by Timus, if you want [(1, "bob"), (2, "is")...]
as output, you can do:
array1 = [1, 3, 5]
array2= [2, 4, 6]
array3 = list(zip(array1 , array2))
print(array3)
# Expected output : [(1, 2), (3, 4), (5, 6)]