folks,
I would like to create the following list, but instead of 3 repetitions, I want 12 repetitions in it. Is there a way to do it without type it 12 times explicitly? Thanks very much for your help.
[(0,pi), (0,pi), (0,pi)]
You can use a list comprehension:
l = [(0, pi) for i in range(12)]
The alternative (multiplying the list) may work for tuple objects because they are immutable, but you will rip hair out when you try it on list objects:
>>> pi = 3
>>> l = [[0, pi]] * 4
>>> l
[[0, 3], [0, 3], [0, 3], [0, 3]]
>>> l[0][1] = 4
>>> l
[[0, 4], [0, 4], [0, 4], [0, 4]] # Wat
I personally stay away from that method for anything other than strings.
This will work with tuples (but not recommended for lists):
myl=[(0,pi)] * 12
gives myl
[(0, 3.14), (0, 3.14), (0, 3.14), (0, 3.14), (0, 3.14), (0, 3.14),
(0, 3.14), (0, 3.14), (0, 3.14), (0, 3.14), (0, 3.14), (0, 3.14)]
As @senderle mentions in a helpful comment below this is a good approach because tuples are immutable. This would not be a safe approach with lists as it could give unexpected results as can be seen in the example below.
Tuples vs Lists:
With tuples:
In [69]: myl=[(0,pi)] * 3
In [70]: myl
Out[70]: [(0, 3.14), (0, 3.14), (0, 3.14)]
In [71]: myl[0][0] = 55
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
----> 1 myl[0][0] = 55
TypeError: 'tuple' object does not support item assignment
With lists:
In [72]: myl=[[0,pi]] * 3
In [73]: myl
Out[73]: [[0, 3.14], [0, 3.14], [0, 3.14]]
In [74]: myl[0][0] = 55
In [75]: myl
Out[75]: [[55, 3.14], [55, 3.14], [55, 3.14]] # every list element changes!