A Step-by-Step Guide to Understanding and Using the * operator in Python with Lists
Learn how to multiply or repeat a list n number of times. Understand when and why you would want to do this, along with examples of code snippets that demonstrate it. …
Learn how to multiply or repeat a list n number of times. Understand when and why you would want to do this, along with examples of code snippets that demonstrate it.
Introduction
Multiplying a list in Python is a common operation, especially for beginners just learning the language. The ‘*’ operator can be used as a quick way to repeat or multiply a list multiple times.
It’s important to understand that multiplying lists in Python doesn’t create a new list with copies of each element - instead, it creates an entirely new list which consists of n repetitions of the original list.
This can be very useful for creating patterns in data (like a 5x5 grid filled with ‘a’, or a 3x3 matrix to store coordinates), as well as simple mathematic operations where you want to calculate many things from one number.
Usage
Suppose we have a list my_list = [1, 2, 3]
. We can multiply it by an integer n
to get another list with length equal to the product of lengths of original lists:
new_list = my_list * n
If you print this new list, you’ll get a total of ‘n’ repetitions of the elements in the original list. For example, if my_list = [1, 2, 3]
and n = 3
, then new_list
would be [1, 2, 3, 1, 2, 3, 1, 2, 3]
.
Code Snippets
my_list = [1, 2, 3]
n = 3
new_list = my_list * n
print(new_list)
This will print: [1, 2, 3, 1, 2, 3, 1, 2, 3]
.
Remember to use the code snippets in a Python file or an interactive Python shell for full functionality.