Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Python List operation

I am new to python. i am learning some basic stuff. I was doing some operation on python list like this three_lists=[]*3 when i execute this piece of code it gives me only one empty list like this[]. Why it is not giving me 3 empty list? some what like this [],[],[]

like image 473
user2991828 Avatar asked Apr 27 '26 18:04

user2991828


1 Answers

It says right in the Python docs

s * n or n * s equivalent to adding s to itself n times

where s is a sequence and n is an int. For example

>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

This is consistent with other sequences as well, such as str

>>> 'hello'*3
'hellohellohello'

If you wanted a list of 3 empty lists you could say

>>> [[] for _ in range(3)]
[[], [], []]
like image 60
Cory Kramer Avatar answered Apr 29 '26 08:04

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!