Table of Content
To add an item to a list of lists in Python, you can follow these steps:
Step 1: Understand the Structure
A list of lists is essentially a list where each element is itself a list. For example:
list_of_lists = [[1, 2], [3, 4], [5, 6]]
Step 2: Adding an Item to a Specific Sublist
If you want to add an item to one of the sublists, you can use the append()
method.
Example:
Suppose you want to add the number 7
to the first sublist [1, 2]
:
list_of_lists[0].append(7)
print(list_of_lists)
Output:
[[1, 2, 7], [3, 4], [5, 6]]
Step 3: Adding a New Sublist
If you want to add an entirely new sublist to the main list:
Example:
Suppose you want to add the sublist [7, 8]
:
list_of_lists.append([7, 8])
print(list_of_lists)
Output:
[[1, 2], [3, 4], [5, 6], [7, 8]]
Step 4: Inserting an Item at a Specific Position
If you need to insert an item into a specific position within a sublist or a new sublist at a specific index:
Example:
Inserting 9
at the beginning of the second sublist [3, 4]
:
list_of_lists[1].insert(0, 9)
print(list_of_lists)
Output:
[[1, 2], [9, 3, 4], [5, 6]]
Example:
Inserting a new sublist [10, 11]
at the second position of the main list:
list_of_lists.insert(1, [10, 11])
print(list_of_lists)
Output:
[[1, 2], [10, 11], [3, 4], [5, 6]]
These are the basic methods to add items to a list of lists in Python.
Discussion