16

Likely a duplicate (sorry). I looked around and couldn't find my answer.

I want to generate a list of n empty strings in a one liner.

I've tried:

>>> list(str('') * 16)
# ['']
>>> list(str(' ') * 16)
# [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
# anything with a char in it is working

The below works, but is there a better way? Why doesn't list(str('') * 16) work?

>>> [str() for c in 'c' * 16]
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
4
  • @AshwiniChaudhary: that's more an answer than a comment, no? Commented Oct 13, 2014 at 4:15
  • @DSM I was looking for a dup, I think this one is good enough: Create List of Single Item Repeated n Times in Python Commented Oct 13, 2014 at 4:17
  • @AshwiniChaudhary Maybe. I would've gotten lost in the length/complexity of that answer. Commented Oct 13, 2014 at 4:18
  • you can use numpy.chararray((size of the string)). Commented Jul 28, 2017 at 18:20

2 Answers 2

24

See the Python standard types page:

>>> [''] * 16
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

s * n, n * s

n shallow copies of s concatenated

where s is a sequence and n is an integer.

The full footnote from the docs for this operation:

Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
Sign up to request clarification or add additional context in comments.

Comments

7

You can multiply out a list like this. Since '' is immutable you don't need to worry that they are all references to the same string.

[''] * 16

You can't use the same trick for mutable objects (eg lists or dicts). You need to use something like your last version

[mutable_thing() for c in range(16)]

or

[[] for c in range(16)]

or

[{} for c in range(16)]

1 Comment

+1 for explaining why this isn't dangerous.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.