Reputation: 11
I'm self-learning Python and ran into a problem I'm having difficulty with.
I'm working with Paul Barry's Headfirst Python.
The list is as follows:
movies = [
"The Holy Grail",
1975,
"Terry Jones & Terry Gilliam",
91,
[
"Graham Chapman",
[
"Michael Palin",
"John Cleese",
"Terry Gilliam",
"Eric Idle",
"Terry Jones",
],
],
]
The code is
print(movies[4][1][3])
to generate Eric Idle
. Yet, I'm unsure what the purpose of the [1]
is here, and how the count generated the response.
Thanks for any help in advance.
Upvotes: 1
Views: 91
Reputation: 16772
Since it a nested list, Indexing comes in handy:
Indexing starts from 0, and not 1.
movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91, ["Graham Chapman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]]
Elaborated:
print(movies[4])
Would give you the 4th
element which is a nested list
print(movies[4][1])
Would give you the 1st
element of that nested list movies[4]
, which is a list
print(movies[4][1][3])
Would give you the 3rd
element of that list movies[4][1]
, which is a str
Hence:
print(movies[4]) # ["Graham Chapman", ["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]
print(movies[4][1]) # ['Michael Palin', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']
print(movies[4][1][3]) # Eric Idle
Upvotes: 2
Reputation: 531055
Let's restructure the definition a little, adding comments on the right indicating the indexes:
movies = [
"The Holy Grail", # [0]
1975, # [1]
"Terry Jones & Terry Gilliam", # [2]
91, # [3]
[ # [4]-begin
"Graham Chapman", # [4][0]
[ # [4][1]-begin
"Michael Palin", # [4][1][0]
"John Cleese", # [4][1][1]
"Terry Gilliam", # [4][1][2]
"Eric Idle", # [4][1][3]
"Terry Jones" # [4][1][4]
] # [4][1]-end
] # [4]-end
]
movies[4]
is a list. movies[4][0]
is "Graham Chapman", and movies[4][1]
is another list, which has "Eric Idle" at index 3.
Upvotes: 3