Home

List multiplication in Python

a = [] * 6
print(a)
>> []


b = [] + []
print(b)
>> []


f = ["" for _ in range(6)]
print(f)
>> ['', '', '', '', '', '']


n = [None for _ in range(6)]
print(n)
>> [None, None, None, None, None, None]


some_list = [5, 10, "The Python Coding Stack", ["another", "list"]]
copied_list = some_list.copy()


# diff ids
print(id(some_list))
print(id(copied_list))
>> 133283441568832
>> 133283441562752


# some_list.copy() - This creates a shallow copy.
# The new list contains the same references as the original list.
print(id(some_list[-1]))
print(id(copied_list[-1]))
>> 133283442269504
>> 133283442269504

List multiplication

Consider this expression: [[]]*6. The outer list is not empty. It contains another list. However, the inner list is empty. But, as we discussed earlier, the outer list doesn’t really contain the inner list. Instead, it contains a reference to it.

Therefore, when you multiply the outer list by 6, you copy the reference to the inner list six times. As it’s the same reference, it refers to the same list. All six slots in films refer to the same inner list.


# same ids
films = [[]] * 6
print(films)
>> [[], [], [], [], [], []]


for film in films:
    print(id(film))

>> 133283453034368
>> 133283453034368
>> 133283453034368
>> 133283453034368
>> 133283453034368
>> 133283453034368


films[0].append("some title")
print(films)
>> [['some title'], ['some title'], ['some title'], ['some title'],
    ['some title'], ['some title']]


# diff ids!
new_films = [[] for _ in range(6)]
for new_film in new_films:
    print(id(new_film))

>> 133283442269696
>> 133283442244736
>> 133283442277824
>> 133283442277888
>> 133283442277760
>> 133283442277632

List Comprehension vs. Multiplication

List Comprehension: [[] for _ in range(6)] This method creates 6 distinct empty lists. Each iteration of the comprehension creates a new empty list object.

List Multiplication: [[]] * 6 This method creates 6 references to the same empty list object.

source: https//www.thepythoncodingstack.com/p/whats-really-in-a-python-list

Tags: Python, List