List | How do I Iterate Through Positions In A Nested List? In Python

Here in this Tutorial, we will discuss How do I Iterate Through Positions In A Nested List? In Python Where we know that a nested list is nothing but a list inside a list or we can say the Elements of a list are also a list.

What Is List In Python?

A list is a mutable non- Primitive data type that can store any kind of data as the elements of the list and can be edited at any time only by accessing the elements using their index numbers as all the elements in the list have a unique index number where the data is stored.Nested List

Nested List In Python

Nested list are those in which a list has elements in which each element have a list as the element we can say the list in a list is the same as a two-dimension Matrix or we can say two dimension array.

The iteration of a nested List Requires two nested For or while loops so that all the elements can be accessed by Nested List Lets understand how does nested list works, Stores the elements and we could access them for our use.

For example, take an example-

list1=[[1,8],[2,5],[3,4],[4,3]]    # Note: each day's item less than previous day's

prev_day, prev_item = list1[0]     # use unpacking to set the first day
count = 0

for curr_day, curr_item in list1[1:]:

    if curr_item < prev_item:
            diff = prev_item - curr_item
            
            print(f"DAY:{curr_day}, DIFFERENCE: {diff}")
            prev_item = curr_item    # reset it to the current one
            count += 1
            
    if count == len(list1) -1:
        
        print("Every Day ITEMS Are Less than Previous Day!")

And here we can see in the example how a list1 has four elements and each of the four elements have two elements which means a two dimension array r a 2 dimension Matrix of 4*2.

Here we can easily see that for treating nested lists we need to use two loops to access each element of the list Outer loop is for accessing the elements of the list whereas, Inner loop is for the inner list which is there in an element for a list.

This makes the complexity of O(n^2) for iteration a nested List and it is the same for Two Dimension array also In this way we can save the memory of storing a variable as lists are stored as nested list but again it becomes O(n^2) for iteration, Editing, Deleting or adding.

Learn More About Nested List: https://stackoverflow.com/questions/75291663/how-do-i-iterate-through-positions-in-a-nested-list

And learn more about list: Linked List Program in Python – Create Linked List, Add Node, Iterrate, and Print Data

Leave a Comment

%d bloggers like this: