Search code examples
pythonlisttraversal

How to traverse multiple lists in Python


I have two equal length lists. I want to traverse them both at the same time in order to perform some operation on each equivalently indexed item of each list.

It seems inefficient to create an index variable to iterate through the lists.

For example, this works:

a=[1,2,3]
b=[7,8,9]
for i in range(0,len(a)):
  print(a[i],b[i])

But can I do it without the index?

I did find: Traversing multiple lists in django template in same for loop but it looks massively complicated for all I want to do and I have no idea what a django template is!


Solution

  • In asking the question and searching some of the keywords I didn't understand, I came up with an example more simple than the one I found, equivalent to my examples above:

    a=[1,2,3]
    b=[7,8,9]
    
    for j in zip(a,b):
      print(j[0],j[1])
    

    This works because zip collates the two lists into a list of lists.

    print(list(zip(a,b)))
    >>> [(1, 7), (2, 8), (3, 9)]
    

    This is certainly a shortcut for coding, but I'm sure there must be an even more efficient way.