1

Is there an elegant way in python to make a list of duplicate things?

For example, I want to make a list of 7 lefts, like so:

x = ['left', 'left', 'left', 'left', 'left', 'left', 'left']

other than doing something like:

x = []
for y in xrange(7):
    x.append('left')

is there a way to efficiently make a list of 7 lefts? I had hoped for something like: x = ['left' * 7], but of course that gives me ['leftleftleftleftleftleftleft'].

Thanks a lot, Alex

Alex S
  • 4,726
  • 7
  • 39
  • 67

5 Answers5

9

If you want (or simply are okay with) a list of references to the same object, list multiplication is what you want:

x = ['left'] * 7

If you need separate objects, e.g. if you're initializing a list of lists, you want a list comprehension:

x = [[] for _ in xrange(7)]
user2357112
  • 260,549
  • 28
  • 431
  • 505
3

What about something like x = ['left'] * 7?

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
3
>>> list = ['left' for x in range(7)]
>>> list
>>>['left', 'left', 'left', 'left', 'left', 'left', 'left']
Xar
  • 7,572
  • 19
  • 56
  • 80
1

['left'] * 7

or

[ 'left' for _dummy in range(7) ]

shx2
  • 61,779
  • 13
  • 130
  • 153
0

Lost comprehension

['Left' for _ in range(7)]
migajek
  • 8,524
  • 15
  • 77
  • 116