1

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?

Ruth
  • 11
  • 1
  • 3
    Hi and welcome. Please do not use list as a variable name as it is a keyword in python – naive Oct 14 '19 at 14:42

2 Answers2

2
list_1 = [1, 2, [3, 4], 5]
new_list = [elem[-1] for elem in list_1 if isinstance(elem, list)]
print(new_list )

Output:

[4]

For getting the last element of a list please refer here.

For list comprehension, see here

naive
  • 367
  • 1
  • 3
  • 9
0

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.

Addie
  • 1,653
  • 5
  • 21
  • 32