0

If I have

colours = [ "red", "green", "yellow"]
animals = [ "mouse", "tiger", "elephant" ]
coloured_animals = [ (x,y) for x in colours for y in things ]

What do I need to add so that the list comprehension returns ("red","mouse"), ("green","tiger"),("yellow","elephant") instead of all pairings?

boson
  • 886
  • 1
  • 12
  • 25

2 Answers2

3

python has the builtin function zip for this

>>> colours = [ "red", "green", "yellow"]
>>> animals = [ "mouse", "tiger", "elephant" ]
>>> zip(colours, animals)
[('red', 'mouse'), ('green', 'tiger'), ('yellow', 'elephant')]
cts
  • 1,790
  • 1
  • 13
  • 27
1

You can use the built-in function zip, but if you wanted to fix your list comprehension, here's how you would do it, provided that len(colours) <= len(animals):

>>> coloured_animals = [(colours[x], animals[x]) for x in range(len(colours))]
>>> coloured_animals
[('red', 'mouse'), ('green', 'tiger'), ('yellow', 'elephant')]
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76