简体   繁体   中英

Python: last element of tuple

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?

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

You can unpack tuples like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM