Sobes.tech
Junior
237

How does list multiplication work in Python?

Answer from AI

sobes.tech AI

Multiplying a list by an integer k in Python creates a new list by repeating the elements of the original list k times. If k is zero or negative, the result will be an empty list. The elements inside the new list are references to the same objects as those in the original list.

# Example of list multiplication
original_list = [1, 2, 3]
multiplied_list = original_list * 3
print(multiplied_list)  # [1, 2, 3, 1, 2, 3, 1, 2, 3]

# Example with mutable objects
mutable_list = [[1], [2]]
multiplied_mutable_list = mutable_list * 2
print(multiplied_mutable_list)  # [[1], [2], [1], [2]]

# Changing the first element in the second nested list
multiplied_mutable_list[1][0] = 99
print(multiplied_mutable_list)  # [[1], [99], [1], [99]]
# Note that the second and fourth nested lists changed,
# because they reference the same object [[2]]

# Example of multiplication by 0 or a negative number
empty_list = original_list * 0
print(empty_list)  # []

negative_list = original_list * -2
print(negative_list)  # []

Comparison table with other list operations:

Operation Description Result
Addition (+) Concatenation of two lists. A new list with elements of both lists.
Multiplication (*) Repetition of list elements. A new list with repeated elements.