2

I would isolate the last element of a tuple like

a = (3,5,5)
last = a[-1]

but the problem is that i have a pice ok code like this

if var == last:
  do something

and it takes the first 5 and not the second, how can i do to take the last one?

6
  • Can you provide more details on the question? What is var ? What is the actual problem you're trying to solve? Commented Apr 14, 2012 at 10:13
  • 2
    How do you know which 5 it is taking? They both look the same to me. :-P Commented Apr 14, 2012 at 10:15
  • var is a variable in this case is 5 Commented Apr 14, 2012 at 10:15
  • 1
    Show your loop/code to allow a better understanding of your question. Commented Apr 14, 2012 at 10:17
  • 2
    Again, what is the problem you have? What you posted is your attempt to solve the problem! Commented Apr 14, 2012 at 10:24

2 Answers 2

12

What you are trying to do is impossible. Those two fives are exactly the same.

However, when iterating over the tuple you can check if you reached the last element like this:

a = (3, 5, 5)
for i, var in enumerate(a):
    if i == len(a) - 1:
        print 'last element:'
    print var

Demo:

In [1]: a = (3, 5, 5)
In [2]: for i, var in enumerate(a):
   ...:     if i == len(a) - 1:
   ...:         print 'last element:'
   ...:     print var
   ...:
3
5
last element:
5
Sign up to request clarification or add additional context in comments.

Comments

0

You can unpack tuples like this:

t = (3, 5, 5)
*_, last = t
assert last == 5

Comments

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.