python - Reserving space for list -


i have make list2 use name list1 number of name in list1 can vary.

foo = ['spam', 'eggs'] bar = [['spam', ['a', 'b']], ['eggs', ['c', 'd']]] 

so, reserve bar by

bar = [[none] * 2] * len(foo) 

and copy names list1 looping

 bar[i][0] = foo[i] 

but result name in every sublist same this

bar = [['eggs', ['a', 'b']], ['eggs', ['c', 'd']]] 

i try reserve by

bar = [[none, none], [none, none]] 

and no issue @ all. think problem come how reserve list.

how can fix this. if don't understand english, please ask. thanks.

create second list this:

list2 = [[none]*2 x in range(len(list1))] 

or alternativly, if reason don't use comprehensions, do

list2 = [] x in range(len(list1)):     list2.append([none,none]) 

the problem when like

[listitem] * numcopies 

you list contains numcopies copies of the same listitem, sublists same - when change 1 change them all.

the way have suggested create unique lists contain same content (two copies of none). changing 1 of these sublists not change others.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -