morgoth84
morgoth84

Reputation: 1140

Iterate through 2 lists with different length in reverse order

I have two lists of items, I don't know their length, but it needn't be the same. I need to add their items to another list as pairs in reversed order. So the last item in list1 is paired with the last item in list2. First items in both lists will be paired only if their lengths are the same.

I have no idea how to do this in Python and in other languages it's pretty easy to do. This is what I've tried so far, but it doesn't work:

blocks = []
list = list1
if len(list2) > len(list1):
    list = list2
r_list1 = reversed(list1)
r_list2 = reversed(list2)

for i, not_used in enumerate(list):
    blocks.append([
        r_list1[i] if len(r_list1) > i else None,
        r_list2[i] if len(r_list2) > i else None,
    ])

Upvotes: 1

Views: 347

Answers (2)

falsetru
falsetru

Reputation: 368954

Using itertools.izip_longest:

>>> import itertools
>>> lst1 = [1,2,3,4]
>>> lst2 = [5,6,7]

>>> itertools.izip_longest(reversed(lst1), reversed(lst2))
<itertools.izip_longest object at 0x0000000002D13228>

>>> list(itertools.izip_longest(reversed(lst1), reversed(lst2)))
[(4, 7), (3, 6), (2, 5), (1, None)]

>>> map(list, itertools.izip_longest(reversed(lst1), reversed(lst2)))
[[4, 7], [3, 6], [2, 5], [1, None]]

If you need another value instead of None, use fillvalue keyword argument:

>>> list(itertools.izip_longest(reversed(lst1), reversed(lst2), fillvalue=999))
[(4, 7), (3, 6), (2, 5), (1, 999)]

Upvotes: 1

YS-L
YS-L

Reputation: 14738

Does this work for you?

a = [1,2,3,4,5]
b = [55,44,33,22]
zip(a[::-1], b[::-1])

Output

[(5, 22), (4, 33), (3, 44), (2, 55)]

Upvotes: 0

Related Questions