List With in the List in Python
In this class, we discuss list with in the list in python.
For Complete YouTube Video: Click Here
List with in the List
To understand the concept of a list with in the list, Reader should have a basic understanding of list data type. Click here.
As we discussed list previously, a list is a collection of compound data types.
Placing a list in the list is possible because the list is a collection of compound data types.
Let’s take examples, and understand how to define a list and access-list within the list.
a=[“C”[“java”,”is”,”a”,”programming”,”language”],”python”,”is”,”programming”,”language”]
In the above example, the first element is of type string.
The second element is of type list.
When we display the above list.
print(a) will show [“C”,[“java”,”is”,”a”,”programming”,”language”],”python”,”is”,”programming”,”language”]
Display first index position element.
Print(a[1]) will display [“java”,”is”,”a”,”programming”,”language”].
The entire list is written in Index position one and considered as an element.
Access elements list within the list
Example:
a=[“C”,[“java”,”is”,”a”,”programming”,”language”],”python”,”is”,”programming”,”language”]
print(a[1][0]) will display java.
In the above print statement, we defined a[1][0]. It means in the first index position. We have a list.
In that list, the zero index position element should be displayed.
Similarly, we can define any number of levels we needed. List within the list within the list.
Example:
a=[“C”,[“java”,”is”,”a”,”programming”,”language”,[“C++”,”is”,”a”,”programming”,”language”]],”python”,”is”,”programming”,”language”]
In the above example, we have three levels of nested lists.
To access the elements present in the nested list. We use square brackets, as shown above.
print(a[1][5][3]) will display programming.
How to take the list from the user input?
a=[] n=int(input("enter the number of elements in the list")) for i in range(0,n): print("enter the element {}".format(i+1)) element=int(input()) a.append(element) print(" the entered list is",a)
The above program shows how to take elements from the user input and create a list.
In this program, we made an empty list.
We are taking the number of elements.
For loop executes for n times.
Each time take an element from the user and append it to the list.
How to take the list within the list from the user input?
a=[] n=int(input("enter the number of elements in the list")) for i in range(0,n): print("enter your name and id") element=[input(),int(input())] a.append(element) print(" the entered list is",a)
From the above program, we are taking the user name and identification number.
Each time it loops. We are taking details and placing them on a list.
The details list is appended to another list.
This is one of the ways we create a list with in the list from the user input.
How is memory assigned to the list? We discuss this in our next class