![]() |
VOOZH | about |
We are given a nested list we need to copy it. For example, we are given a nested list a = [[1, 2], [3, 4], [5, 6]] and we need to copy it so that output should be [[1, 2], [3, 4], [5, 6]].
To copy a nested list using a for loop, we iterate over each sublist and create a new list for each sublist to ensure nested structure is preserved. This creates a shallow copy where inner lists are copied but the inner elements are still references to the original ones.
[[1, 2], [3, 4], [5, 6]]
Explanation:
Using list comprehension we can create a new list by iterating over each sublist in the original list and making a shallow copy of each sublist with sublist[:]. This results in a new nested list where the inner lists are independent of the original ones.
[[1, 2], [3, 4], [5, 6]]
Explanation:
Using map() with list() in Python applies a function to each item in an iterable and returns a new list.
Original List: [[1, 99], [3, 4], [5, 6]] Copied List: [[1, 2], [3, 4], [5, 6]]
Explanation: