2

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

1
  • Yeah, looks like that's pretty much the same question, sorry. Commented Dec 22, 2013 at 22:34

5 Answers 5

10

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)]
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

3
>>> list = ['left' for x in range(7)]
>>> list
>>>['left', 'left', 'left', 'left', 'left', 'left', 'left']

Comments

1

['left'] * 7

or

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

Comments

0

Lost comprehension

['Left' for _ in range(7)]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.