Nested Lists in Python

Nested Lists in Python

Totoro matryoshka doll in a data structure

What are nested lists? Put simply, they are lists within lists. A list is a data structure in Python that can contain any type of object, including other lists. Nested lists are useful for creating hierarchical data structures that contain categories of data based on sub-elements. While a nested list can nest infinitely, it would be wise to limit more than 3 nested sublists so other developers can follow the nesting levels. We can always break it up for better readability.

To access elements with a regular list or array, we have to reference the element's index. Starting from zero, each element within a list or string is indexed according to its order.

To access items within nested lists, multiple indexes are used together to reference elements within the list inside another list.

Because lists are mutable data structures in Python, elements within nested lists can be modified or assigned new values using the indexes.

B = [ 
[2,5,4], 
[3,5,7], 
[4,7,8] ]

print( B[0][0], B[0][1], B[0][2] )
# Prints "2 5 4"

B[0][0] = 9
B[0][1] = 'a'

print( B[0][0], B[0][1], B[0][2] )
# Now prints "9 a 4"

Hacker Rank Nest Loop Exercise

Try this problem here!

*Given the names and grades for each student in a class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.

Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.*

So, we need to take names and scores of students and store them in a list. This is a nested list because each student will be represented by a list of their name and score within the larger group of students, which is the outer list. In the code below, group represents the outer list and person is the nested list.

 group = []
    for _ in range(int(input())):
        person = []
        person.extend([input(), float(input())])
        group.append(person)

The list method extend is used above to create the nested list by creating a list of two inputs based on the number of students provided by the user.

Now we need to sort the list by the second element of the sublists. There are many sorting algorithms but the lambda expression is the most concise way to express it.

def lambda_sort(sublist):
    # key is set to sort using second element of
    # sublist using lambda
    sublist.sort(key=lambda x: x[1])
    return sublist

We need to now remove the lowest score and display the second lowest score. Since the second lowest score can have multiple student names, the code below removes all instances of the lowest score and returns all instances of the second lowest.

    sorted_group = lambda_sort(group)

    if len(sorted_group) <= 1:
        print(sorted_group[0][1])

    elif len(sorted_group) > 1:

        first = sorted_group[0][1]

        #Remove all instances of lowest score
        for elem in range(0, len(sorted_group)):
            for i in sorted_group:
                for item in i:
                    if item == first:
                        sorted_group.remove(i)

        second_lowest = sorted_group[0][1]

        #Add all instances of second lowest to final nested list
        final = []
        for person in sorted_group:
            if person[1] == second_lowest:
                final.append(person[0])

        #Sort final list to display in alphabetical order
        final.sort()
        for i in final:
            print(i)

Nice! Now we get the second lowest scoring student names displayed, no matter how many instances of that value are present in the original nested list.

While this code works for the problem, it could be optimized. How would you do it?

Full code is here on my Github.