Thursday, January 16, 2025
HomeProgrammingWhy does appending to one list in a list of lists also...

Why does appending to one list in a list of lists also append to all the other lists?

Appending to one list in a list of lists affects all other lists if they reference the same object. In Python, lists are mutable, and when you create a list of lists using a shared reference, all sublists point to the same memory location. Modifying one sublist changes all of them because they are not independent copies.

See also  How to Use Java JOptionPane

Example:

lists = [[1]] * 3 # All sublists share the same reference
lists[0].append(2) # Affects all sublists
print(lists) # Output: [[1, 2], [1, 2], [1, 2]]

To avoid this, use copy() or list comprehensions to create independent sublists.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x