Slaknation
Slaknation

Reputation: 1926

Python: for loop up to the shorter of two lists

I want to do a for loop with two lists that takes the shorter of the two and only goes up to that:

list1 = [1, 2, 3]
list2 = ['a', 'b']

for val in (list1 up to length of list2)
    print val

output should be:

1
2

Upvotes: 1

Views: 588

Answers (1)

Djaouad
Djaouad

Reputation: 22776

You can use zip():

list1 = [1, 2, 3]
list2 = ['a', 'b']
for a, b in zip(list1, list2):
  print(a)
#1
#2

If you want to do it manually, use this:

list1 = [1, 2, 3]
list2 = ['a', 'b']
m = min(len(list1), len(list2)) # get the minimum length
for i in range(m):
  print(list1[i])
#1
#2

However, I would recommend zip(), since it does everything for you. It's just good to be able to do something without having to depend on special programming language features.

Upvotes: 6

Related Questions