![]() |
VOOZH | about |
A 2D list in Python is a list of lists where each sublist can hold elements. Appending to a 2D list involves adding either a new sublist or elements to an existing sublist. The simplest way to append a new sublist to a 2D list is by using the append() method.
[[1, 2], [3, 4], [5, 6]]
Explanation:
append() adds a new sublist [5, 6] as a single element to the 2D list.Let's explore some other methods to append to 2D List in Python
Table of Content
If we want to append an element to an existing sublist in the 2D list, you can directly append it to that sublist.
[[1, 2], [3, 4, 5]]
Explanation:
a[1]) then apply append() to add an element.+=+= operator allows you to extend a sublist with multiple elements in a concise manner.
[[1, 2, 5, 6], [3, 4]]
Explanation:
+= modifies the sublist in place by appending elements from another list.extend().If we want to append multiple sublists dynamically list comprehension is a concise option.
[[1, 2], [3, 4], [5, 6], [7, 8]]
Explanation:
extend() to Flatten a 2D ListIf we wish to merge another 2D list into the current one extend() is an efficient choice.
[[1, 2], [3, 4], [5, 6], [7, 8]]
Explanation:
extend() adds elements of another iterable to the list without nesting.