Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create n empty strings in one line [duplicate]

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]
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
like image 874
Jess Avatar asked Oct 13 '14 04:10

Jess


1 Answers

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]]
like image 152
agf Avatar answered Sep 23 '22 01:09

agf