0

So I have this list

X = [[1,2,3],[1,2,3],[1,2,3]]

How can I access all the last elements like Y = [3,3,3]?

Y=X[0:2][2] doesn't seem to work

4 Answers 4

9

I think a list comprehension would be the easiest way to do this. https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Y = [i[-1] for i in X]

The -1 will get the last element of the lists. but this can be changed to get any element from these lists.

Sign up to request clarification or add additional context in comments.

1 Comment

I up voted your answer, but your code will break if the sub-list in the OP's list are greater than three elements. Instead of using "hard-coding" to get the last element, use i[-1] to always get the last element.
4

Use [-1] to acces last item in list.

x_last = [i[-1] for i in X]

Comments

0

zip is an alternative:

>>> X = [[1,2,3],[1,2,3],[1,2,3]]
>>> list(list(zip(*X))[-1])
[3, 3, 3]
>>>

Comments

0
Y = [m[-1] for m in X]

The index -1 means the last element of a list.

2 Comments

Triple ticks don't work on SO unfortunately. You have to indent everything by four spaces to get the same effect.
@MadPhysicist What are you saying about?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.