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) ?
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.
new_list = [var for i in range(8)]var is not a mutable object, or the OP is in for a nasty surprise.8 or any number n instances of var is.You can use list comprehension syntax:
new_list=[var for i in range(8)]
_ instead of i if its unused, but other then that, I like this way bettervar were an expression that evaluated to a new copy each time (like [], or spam.make_eggs() or even, as Joran suggests, copy(var) or var[:]), this would be the right solution (assuming you wanted 8 new copies instead of the same object 8 times). Otherwise, it's just misleading—it seems like it's avoiding the * 8 trap, but it really isn't.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.
var? A mutable or an immutable object?