In this post, we will see how to create a list of lists in python.
It is quite easy to create list of lists in Python. You just need to use list’s append method to create list of lists.
Here is simple example to create list of lists in Python.
1 2 3 4 5 6 7 8 |
list1=[1,2,3,4] list2=[5,6,7,8] listoflists= [] listoflists.append(list1) listoflists.append(list2) print("List of Lists:",listoflists) |
Output:
List of Lists: [[1, 2, 3, 4], [5, 6, 7, 8]]
How can we access element from list of lists in Python
You need to provide index of list from list of lists and then index of element you want to fetch from that list.
For example:
Let’s say you want to access element 7 from list of lists then you need to write listoflists[1][2]
1 2 3 4 5 6 7 8 9 10 |
list1=[1,2,3,4] list2=[5,6,7,8] listoflists= [] listoflists.append(list1) listoflists.append(list2) print("List of Lists:",listoflists) print("3rd element from 2nd list:",listoflists[1][2]) |
Output:
List of Lists: [[1, 2, 3, 4], [5, 6, 7, 8]]
3rd element from 2nd list: 7
That’s all about how to create list of lists in Python.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.
Thanks, this really helped me.
I kept doing list1.append(list2), which does not work for me at all.
Python is really hard for me. I am a J language freak.