Jun-12-2024, 10:41 AM
Hi pythonists! This is my first post there... I faced with a question when I needed to create a list with a number of empty lists. I found two approaches:
1. ls = [[] for _ in range(9)]
2. ls = [[]] * 9
And after I printed them and their types I got the same results:
[[], [], [], [], [], [], [], [], []]
[[], [], [], [], [], [], [], [], []]
<class 'list'>
<class 'list'>
However when I was solving this task and checked the solution (available by the link too) from leetcode these lists worked in different ways - only with the second I got right result. What is the difference between them?
1. ls = [[] for _ in range(9)]
2. ls = [[]] * 9
And after I printed them and their types I got the same results:
a = [[]] * 9 b = [[] for _ in range(9)] print(a) print(b) print(type(a)) print(type(b))results:
[[], [], [], [], [], [], [], [], []]
[[], [], [], [], [], [], [], [], []]
<class 'list'>
<class 'list'>
However when I was solving this task and checked the solution (available by the link too) from leetcode these lists worked in different ways - only with the second I got right result. What is the difference between them?