0

Say I have two list

firstlist = ['A','B','C','D','E']

secondlist = ['1','2','3','4','5','6','7','8','9','10']

I want to combine one item in firstlist with another item in secondlist

So I can I have:


[('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5'), ('A', '6'), ('B', '7'), ('C', '8'), ('D', '9'), ('E', '10')]

I know I could use the zip function but since one list is longer, it would stop at the shorter list

coderoftheday
  • 1,987
  • 4
  • 7
  • 21
  • 1
    Does this answer your question? [Is there a zip-like function that pads to longest length in Python?](https://stackoverflow.com/questions/1277278/is-there-a-zip-like-function-that-pads-to-longest-length-in-python) – Stef Oct 28 '20 at 13:13
  • Wait, no, it doesn't. What you want is to combine `zip` with `itertools.cycle`. – Stef Oct 28 '20 at 13:15
  • that will leave some values as ```None``` – coderoftheday Oct 28 '20 at 13:15
  • Exactly Stef. You are right. Post your comment as an answer. – Sushil Oct 28 '20 at 13:16
  • OK, this one should answer your question: [How to zip two differently size lists](https://stackoverflow.com/questions/19686533/how-to-zip-two-differently-sized-lists) and [this answer](https://stackoverflow.com/a/53892180/3080723) if you need iterables instead of lists and you don't know which one is shorter – Stef Oct 28 '20 at 13:25

2 Answers2

2

Below code will help you to print a new list as expected

from itertools import cycle 

firstlist = ['A','B','C','D','E']
secondlist = ['1','2','3','4','5','6','7','8','9','10']

res = [[x, y] for x, y in zip(cycle(firstlist), secondlist)] 
print(res)
Ananth
  • 787
  • 5
  • 18
1

What you want is to combine zip with itertools.cycle:

import itertools
def zip_cycle_first(a, b):
  return zip(itertools.cycle(a), b)

If you don't know which one of a or b is longer, you can add a test for the length if they are lists:

import itertools
def zip_cycle_shortest_list(a, b):
  if len(a) > len(b):
    return zip(a, itertools.cycle(b))
  else:
    return zip(itertools.cycle(a), b)

If you don't know which one is longer and they are both iterables, this answer gives a more versatile solution using itertools.tee in combination with itertools.zip_longest.

Stef
  • 13,242
  • 2
  • 17
  • 28