1

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)]

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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!

3 Comments

It might be worth mentioning that this approach works because tuples are immutable; with mutable objects it may produce unexpected results (unless you expect those results and they're desirable).
@Levon: (edits) Tuples are immutable. They cannot be modified after you create them.
@Blender Thanks Blender, that was some typo!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.