user2913243
user2913243

Reputation: 23

Repeat a variable in python

let var be my variable. I want to create a list like this :

new_list=[var,var,var,var,var,var,var,var]

how to do it (not manually, obviously) ?

Upvotes: 2

Views: 5445

Answers (3)

tinylambda
tinylambda

Reputation: 161

You can also use itertools.repeat to do that:

>>> from itertools import repeat
>>> repeatvars = repeat('var', 8)
>>> repeatvars
repeat('var', 8)
>>> list(repeatvars)
['var', 'var', 'var', 'var', 'var', 'var', 'var', 'var']

and there are many useful functions under the itertools module, you can learn it from this site, hope that will help.

Upvotes: 1

urish
urish

Reputation: 9033

You can use list comprehension syntax:

 new_list=[var for i in range(8)]

Upvotes: 2

Rostyslav Dzinko
Rostyslav Dzinko

Reputation: 40755

You can do it with multiplication operator:

new_list = [var] * 8

Also remember that variables store references to objects in Python, so:

ob = MyObject()
new_list = [ob] * 8

will create a list consisting of 8 references to the same object. If you change it - all of them change.

Upvotes: 5

Related Questions