Skip to content
Home » List Repetition in Python

List Repetition in Python

Spread the love

Today we’ll learn how repetition works with lists.

Here’s the video version of the article:

You can use the * operator to repeat the elements of a list:

>>> letters = ["n", "q", "w"]
>>> letters * 3
['n', 'q', 'w', 'n', 'q', 'w', 'n', 'q', 'w']

You can also apply the repetition operator to nested lists. Here’s a list called codes:

>>> codes = [17, 5, 41]

The list codes becomes an element of a larger list. The element of the outer list, which is the inner list, is then repeated 4 times:

>>> triplets = [codes] * 4  
>>> triplets
[[17, 5, 41], [17, 5, 41], [17, 5, 41], [17, 5, 41]] 

Now let’s change the second element in the first inner list from 5 to 30:

triplets[0][1] = 30

Turns out the element was changed in each of the inner lists. This is because the repetition operator creates four references to the list codes:

>>> triplets
[[17, 30, 41], [17, 30, 41], [17, 30, 41], [17, 30, 41]]
list repetition

This is because of shared references. If you want to learn more about them, you can read this article.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply