14

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]
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
Jess
  • 3,097
  • 2
  • 16
  • 42
  • @AshwiniChaudhary: that's more an answer than a comment, no? – DSM Oct 13 '14 at 04: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](http://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times-in-python) – Ashwini Chaudhary Oct 13 '14 at 04:17
  • @AshwiniChaudhary Maybe. I would've gotten lost in the length/complexity of that answer. – Jess Oct 13 '14 at 04:18
  • you can use numpy.chararray((size of the string)). – Lov Verma Jul 28 '17 at 18:20

2 Answers2

20

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]]
agf
  • 171,228
  • 44
  • 289
  • 238
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)]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502