[Tutor] list generation

Alan Gauld alan.gauld at yahoo.co.uk
Mon May 10 17:15:06 EDT 2021


On 10/05/2021 19:59, Ed Connell wrote:
> What is the best way to create a list of constant values of a given length?
> 
> gen_list( 78, 4 ) should generate [ 78, 78, 78, 78  ].
> 
> and
> 
> gen_list( 'pop', 2 ) should produce [ 'pop', 'pop' ]


If it is simple literal values as shown then the multiplication operator
works.

multi = [val] * number

But be aware that it produces a list with multiple references to
the same object so, if the object is more complex, specifically
if it is mutable(list, dictionary,set,instance), then changing
one element will change the others too.

problem = [[1]] * 3   #->[[1],[1],[1]]
problem[0].append(2)  #->[[1,2],[1,2],[1,2]]  !!

In that case a list comprehension is preferred:

no_prob = [[1] for n in range(3)]
no_prob[0].append(2)   #->[[1,2],[1],[1]]

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list