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,178
  • 4
  • 33
  • 62

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
  • 235,058
  • 25
  • 372
  • 444
3

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

Paulo Bu
  • 28,366
  • 6
  • 72
  • 72
3
>>> list = ['left' for x in range(7)]
>>> list
>>>['left', 'left', 'left', 'left', 'left', 'left', 'left']
Xar
  • 6,784
  • 14
  • 50
  • 72
1

['left'] * 7

or

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

shx2
  • 57,957
  • 11
  • 121
  • 147
0

Lost comprehension

['Left' for _ in range(7)]
migajek
  • 8,374
  • 14
  • 73
  • 115