Skip to content Skip to sidebar Skip to footer

Storing Lists Within Lists In Python

I have a question about accessing elements in lists. This is the code: movies = ['The Holy Grail', 1975, 'Terry Jones and Terry Gilliam', 91, ['Graham Champman', ['Michae

Solution 1:

Your list is separated into values.

# movies: values0."The Holy Grail"1.19752."Terry Jones and Terry Gilliam"3.914. ["Graham Champman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]

/!\ The index begin from 0

The last value is also separated into values:

# movies[4]: values0."Graham Champman"1. ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]

And the last value is also separated into other values:

# movies[4][1]: values0."Michael Palin",
1."John Cleese"2."Terry Gilliam"3."Eric Idle"4."Terry Jones"

So calling movies[4] returns the last element of movies:

["Graham Champman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]

Typing movies[4][1] returns this:

["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]

And typing movies[4][1][3] returns that:

"Eric Idle"

Tree view

movies
 0. | "The Holy Grail"
 1. | 1975
 2. | "Terry Jones and Terry Gilliam"
 3. | 91
 4. |____
    4.0. | "Graham Champman"
    4.1. |____
        4.1.0 | "Michael Palin"
        4.1.1 | "John Cleese"
        4.1.2 | "Terry Gilliam"
        4.1.3 | "Eric Idle"
        4.1.4 | "Terry Jones"

Hope that helped.

Solution 2:

Please review The Python Tutorial to familiarize yourself with Python basics. Lists in Python can be indexed (starting with 0) and accessed using square brackets.

In your case, sub_ele = movies[4] is accessing the fifth element of the list movies, which is (in this case) a list of length two. Hence subsub_ele = sub_ele[1] is accessing the second element of the sub list, which is (in this case) a list of length five. Lastly, subsub_ele[3] is accessing the fourth element of the sub sub list, which is finally "Eric Idle".

Hopefully, it is now clear.

Post a Comment for "Storing Lists Within Lists In Python"