In this tutorial, we will learn how to create sublists in Python. Python is a versatile language that provides the flexibility to handle multiple data types. Similarly, Python lists, which are collection data types, can hold various types of items.
One list can hold integers, floats, strings, and even other lists. These lists within lists are known as sublists or nested lists. They are particularly useful when dealing with multidimensional data, for instance, when you want to represent matrix-like data structures.
Creating a Sublist
Creating a sublist is quite straightforward in Python. Let us create a list and then create a sublist within that list.
# Creating a list mainlist = ['apple', 'banana', 'cherry'] # Sublist sublist = [1, 2, 3, 4, 5] # Adding sublist to mainlist mainlist.append(sublist) print(mainlist)
When we run the above code, we can expect the following output.
['apple', 'banana', 'cherry', [1, 2, 3, 4, 5]]
Accessing Elements from a Sublist
Just like any other list in Python, we can access elements from a sublist using index values. Here’s how to do it.
# Accessing elements from mainlist print(mainlist[3]) # Outputs the whole sublist print(mainlist[3][1]) # Outputs the second element of the sublist
Upon successful execution of the above code, this will be the output.
[1, 2, 3, 4, 5] 2
Modifying Sublist
We can modify the sublist in the same as we could modify the main list. Here’s how it’s done.
# Changing the second element of sublist mainlist[3][1] = 'two' print(mainlist)
After running the above code, this would be the output.
['apple', 'banana', 'cherry', [1, 'two', 3, 4, 5]]
# Full Code # Creating a list mainlist = ['apple', 'banana', 'cherry'] # Sublist sublist = [1, 2, 3, 4, 5] # Adding sublist to mainlist mainlist.append(sublist) print(mainlist) # Accessing elements from mainlist print(mainlist[3]) # Outputs the whole sublist print(mainlist[3][1]) # Outputs the second element of the sublist # Changing the second element of sublist mainlist[3][1] = 'two' print(mainlist)
Conclusion
Creating sublists and accessing their elements can be easily done in Python. This tutorial has walked you through creating sublists, accessing their elements, and modifying sublists using simple Python instructions.
Sublists in Python are beneficial when dealing with complex data types, and can be very useful in data handling and processing.