1

I'm trying to build a poly-alphabetic cipher but I can't find a way of adding a smaller list into a larger list, I have tried with list comprehensions, but still cannot do it. Please help! I want the smaller list to keep adding the same numbers to the larger list

so lets say I have 2 lists like this:

x = [1,2,3]
y = [4,5,6,7,8,9]
z = [i + j for i,j in zip(x,y)]

the result is the following

print(z)
[5,7,9]

how can I make it so it is:

[5,7,9,8,10,12]

meaning it keeps adding the same numbers to the longer list, thank you for the help

MAUCA
  • 49
  • 11
  • That's because `zip` function stops on the shortest iterator. Because your first list has 3 elements, it would stop after 3 iterations. You can find an answer here - https://stackoverflow.com/a/1277311/840582 – Chen A. Aug 31 '17 at 17:46
  • @Vinny The link you shared does not solve this problem. This question wants to loop back and re-use the values again, that link shows how to pad out default values after the end of the shorter list. – Cory Kramer Aug 31 '17 at 17:48
  • You're right, my bad. I missed that part of re-iterate values. – Chen A. Aug 31 '17 at 18:37

3 Answers3

5

You can use itertools.cycle to loop back through x as needed

>>> import itertools
>>> x = [1,2,3]
>>> y = [4,5,6,7,8,9]
>>> z = [i + j for i, j in zip(itertools.cycle(x), y)]
>>> z
[5, 7, 9, 8, 10, 12]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

This is the simplest way, I think: z = [y[i] + x[i % len(x)] for i in range(len(y))]

Cuber
  • 713
  • 4
  • 17
0
x = [1,2,3]
y = [4,5,6,7,8,9]
z=[a+b for a,b in zip((x*(int(len(y)/len(x))))[:len(y)],y)]

How about this with zip

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44