Create list of lists

Create list of lists in Python

This tutorial guides you on how to create list of lists in Python programming language using dynamic lists and simple lists. Also you will learn how to access item from list of lists.  

Create list of lists – dynamic

Create list of lists

In the following example, you will be creating two dynamic lists and then create list of lists (dynamic lists) in the for loop.

listOfLists = []
myfirstlist = []
mysecondlist = []
n = 10
for i in range (0,n):
    myfirstlist.append(i)  
    mysecondlist.append(n-i)   
    if len(myfirstlist) > 3 and len(mysecondlist) > 3:
        myfirstlist.remove(myfirstlist[0]) 
        mysecondlist.remove(mysecondlist[0])
        listOfLists.append((list(myfirstlist), list(mysecondlist)))        
print (listOfLists)

Note, the lists myfirstlist, mysecondlist are created dynamically in for loop in a way we wanted as shown in the output. After that you create a copy of whole list using the list constructors list(myfirstlist) and list(mysecondlist).

Finally, use append() method of list to create list of lists with the following command.

listOfLists.append((list(myfirstlist), list(mysecondlist)))

Output

[([1, 2, 3], [9, 8, 7]), ([2, 3, 4], [8, 7, 6]), ([3, 4, 5], [7, 6, 5]), ([4, 5, 6], [6, 5, 4]), 
([5, 6, 7], [5, 4, 3]), ([6, 7, 8], [4, 3, 2]), ([7, 8, 9], [3, 2, 1])]

How to access items from list of lists ?

You can access items from list of lists. For example, to access [8,7,6], you need to use indexes appropriately as shown below.

>>> print(listOfLists[1][1])
[8, 7, 6]

List of lists creation – Simple

In the above section we have seen how to create dynamic list of lists. If you have predefined list as shown below: list1 and list2, you can use simply append() method to create list of lists.

For example,

list1 = [10,20,30,40]
list2 = [11,22,33,44]
listOfLists = []
listOfLists.append(list1)
listOfLists.append(list2)
print('list of lists: ', listOfLists)

Output

list of lists:  [[10, 20, 30, 40], [11, 22, 33, 44]]

Similarly, to access second element from the second list in the list of lists:

#2nd element from 2nd list
print(listOfLists[1][1])
22

That’s it. You had learnt how to form list of lists with simple and complex/dynamic lists.

Hope it is helpful 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments