1

I'm wondering if I have a list of the list like this:

a = [[43,76],[8,3],[22,80],[71,9]]

If I want to retrieve the second value in the last 3 sub-lists, i.e the second value from index 1 to 3 would be like that:

a[1:3][1]:

3
80
9
LamaMo
  • 576
  • 2
  • 8
  • 19

4 Answers4

3

My 2c:

[x[1] for x in a[-3:]]

[3, 80, 9]

Demo

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
1

You can use negative slicing here.

print(*[x[1] for x in a[-3:]],sep='\n') #a[-3:] gives last 3 elements
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
0

No, that gets evaluated like this:

a[1:3][1] -> [[8, 3], [22, 80]][1] -> [22, 80]

Note that :3 means up to index 3 (not including it), so really your slice should be a[1:4], but where you want the last three sublists, and not the second to fourth sublists, you should use a negative slice: a[-3:]. Even if the list can only ever be 4-long, this is clearer.

So you want [x[1] for x in a[-3:]]

If you want to print them like in your example output:

>>> for x in a[-3:]:
...     print(x[1])
... 
3
80
9
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Possibly the easiest way to do this as most of the other answers have suggested is:

[x[1] for x in a[-3:]]

However, for practice and for getting used to other ways of solving problems involving lists (and others), it is good to read up on what map, filter and reduce do (assuming that it is not known already). A small description is here.

I thought I'd leave this answer here to add to the other answers. This is another way to do it using map.

[*map(lambda x: x[1], a[-3:])]

Output: [3, 80, 9]

Hope this helps.

Rahul P
  • 2,493
  • 2
  • 17
  • 31
  • Not sure why this got down voted, as well as some other valid answers in this question. Please provide an explanation for the down vote. – Rahul P Mar 03 '20 at 18:54