-1

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()
Timus
  • 10,974
  • 5
  • 14
  • 28
  • You can only return one value. WHat exactly do you want to be the output of `help()`? – user2390182 Oct 22 '21 at 07:08
  • don't use help() as name of function in your program because there is a built-in help() function in python and defining custom one with same name might confuse others in future if they initially look at last line of code. – Kunal Sharma Oct 22 '21 at 07:11
  • Then how can i pass the first item? I will then run the function again as required. Unless there is a better way? – user16710824 Oct 22 '21 at 07:11
  • @user16710824 why don't you try a list of tuples to return all at once. – Kunal Sharma Oct 22 '21 at 07:12
  • The data has come from a pandas .tolist() funtion. Is that an option with this kind of output data? I am only very new at this.... Can you explain please? I think it sounds like what I am essentially trying to do. – user16710824 Oct 22 '21 at 07:15

1 Answers1

0

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)]
polypode
  • 501
  • 3
  • 14
  • The order ends up what I need, but I need each 'first item' in a list, then each 'second item' in a list within the array. Aiming for [[1,2],[3,4],[5,6]] ultimately. Does it make a difference if they are named as array or list? – user16710824 Oct 22 '21 at 07:26
  • @user16710824 Then use `list(zip(alist, blist))` – Timus Oct 22 '21 at 07:30
  • If I can then convert the tuples to lists this answers my question. Thanks – user16710824 Oct 22 '21 at 07:50
  • @user16710824 Apparently you can : https://stackoverflow.com/questions/16296643/convert-tuple-to-list-and-back – polypode Oct 22 '21 at 07:57