Monday 15 February 2010

python - Create n empty strings in one line -



python - Create n empty strings in one line -

this question has reply here:

create list of single item repeated n times in python 6 answers

likely duplicate (sorry). looked around , couldn't find answer.

i want generate list of n empty strings in 1 liner.

i've tried:

>>> list(str('') * 16) # [''] >>> list(str(' ') * 16) # [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] # char in working

the below works, there improve way? why doesn't list(str('' * 16)) work?

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

see python standard types page:

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

s * n, n * s

n shallow copies of s concatenated

where s sequence , n integer.

the total footnote docs operation:

values of n less 0 treated 0 (which yields empty sequence of same type s). note copies shallow; nested structures not copied. haunts new python programmers; consider:

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

what has happened [[]] one-element list containing empty list, 3 elements of [[]] * 3 (pointers to) single empty list. modifying of elements of lists modifies single list. can create list of different lists way:

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

python python-2.7

No comments:

Post a Comment