Create n blank lines on one line

Most likely a duplicate (sorry). I looked around and couldn't find an answer.

I want to create a list of n

empty strings in one liner.

I tried:

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

      

Below works, but is there a better way? Why list(str('') * 16)

does it work?

>>> [str() for c in 'c' * 16]
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

      

+4


source to share


2 answers


See the Python standard types page :

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

      

s * n, n * s

n shallow copies of s-concatenated

where s

is a sequence and a n

is an integer.

Full footnote from the docs for this operation:



Values ​​of n less than 0 are treated as 0 (which gives 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 the following issues:

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

      

What happened is that [[]] is a one-element list containing an empty list, so all three elements from [[]] * 3 (point to) this single empty list. Changing one of the list items changes that single list. You can create a list of different lists like this:

>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

      

+6


source


You can propagate a list like this. Since ''

is immutable , you do not need to worry about all references to the same string.

[''] * 16

      

You cannot use the same trick for mutable objects (like lists or dicts). You need to use something like your latest version

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

      



or

[[] for c in range(16)]

      

or

[{} for c in range(16)]

      

+2


source







All Articles