I'm working on a homework set and I need some help. I have a list that looks like this:
list = [1, 2, [3, 4], 5]
The problem is asking me to use list slicing to extract the last element of the nested list. Can someone help me with this?
I'm working on a homework set and I need some help. I have a list that looks like this:
list = [1, 2, [3, 4], 5]
The problem is asking me to use list slicing to extract the last element of the nested list. Can someone help me with this?
If you're just trying to get one element, then you just need to get the index of that element. In this case the external list has 4 elements:
Index 0 1 2 3
Value 1 2 [3,4] 5
The internal list has 2 elements:
Index 0 1
Value 3 4
So what you need to do is get the index of the internal list, 2
, and the index of the last element in the internal list 1
or -1
(index -1
always gets the last element in a list):
element = list[2][1]
Note: list
is a reserved keyword in python so do not use it for variable naming.