LamaMo
LamaMo

Reputation: 626

Retrieve a range of values from list

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

Upvotes: 1

Views: 171

Answers (4)

Rahul P
Rahul P

Reputation: 2663

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.

Upvotes: 0

wjandrea
wjandrea

Reputation: 32928

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

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 98881

My 2c:

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

[3, 80, 9]

Demo

Upvotes: 3

Ch3steR
Ch3steR

Reputation: 20669

You can use negative slicing here.

print(*[x[1] for x in a[-3:]],sep='\n') #a[-3:] gives last 3 elements

Upvotes: 1

Related Questions