Avt
Avt

Reputation: 17053

Pythonic way to add several identical values to a list

What is the most pythonic way to add several identical values to a list? Of course I can do it with loop or like

someList += [someValue for i in range(someNumber)]

But may be there is a better way or a function?

Upvotes: 0

Views: 215

Answers (4)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

If someValue is immutable, you can use multiplication:

someList += [someValue] * someNumber

This creates someNumber references to the same someValue object. This means that if someValue is a mutable object you'll see changes to that object reflected across all those references.

So for mutable types, you generally use a list comprehension to make sure a new object is created. To extend a list, instead of += you could also use list.extend() with a generator expression:

someList.extend(['extra', 'list', 'elements'] for _ in range(someNumber))

Demo:

>>> someList = ['foo', 'bar', 'baz']
>>> someList += ['spam'] * 5
>>> someList
['foo', 'bar', 'baz', 'spam', 'spam', 'spam', 'spam', 'spam']

and with a mutable object (a list in this case):

>>> someList = ['foo', 'bar', 'baz']
>>> someList += [['spam']] * 5
>>> someList
['foo', 'bar', 'baz', ['spam'], ['spam'], ['spam'], ['spam'], ['spam']]
>>> someList[-1].append('ham')
>>> someList
['foo', 'bar', 'baz', ['spam', 'ham'], ['spam', 'ham'], ['spam', 'ham'], ['spam', 'ham'], ['spam', 'ham']]
>>> someList[-1] is someList[-2]
True

Upvotes: 4

miradulo
miradulo

Reputation: 29720

Why not use the * multiplicative operator, like so:

someList += [someValue] * someNumber

Note that this will make reference to the same element each time, and thus could produce undesired results if you are working with mutable types.

Example:

>>>someList = [5]
>>>someList += [10] * 10
>>>someList
[ 5, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

Alternatively, if you don't want to be referencing the same element each time (perhaps a mutable type, etc.), you can always use a list comprehension as you are doing to create new elements for each list item:

someList += [10 for i in range(10)]

Upvotes: 2

DJG
DJG

Reputation: 6563

You could use the repeat function from itertools to make it clearer to the reader that what you are doing is repeating a value before adding it to a list:

import itertools as it
someList += it.repeat(someValue, someNumber)

Of course, I don't think your original code is unreadable or unpythonic to begin with...

Upvotes: 1

itzMEonTV
itzMEonTV

Reputation: 20369

try this if somevalue is immutable

someList += [somevalue] * somenum

Upvotes: 2

Related Questions