Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack parts of a tuple into tuple

I have a tuple like this

t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')

and I want to extract the first 6 values as tuple (in order) and the last value as a string.

The following code already works, but I am wondering if there is a "one-liner" to achieve what I'm looking for.

# works, but it's not nice to unpack each value individually
cid,sc,ma,comp,mat,step,alt = t 
t_new = (cid,sc,ma,comp,mat,step,)
print(t_new, alt) # (1, '0076', 'AU', '9927016803A', '9927013903B', '0010') VO

This is very close to what I'm looking for, but it returns the first values as a list instead of a tuple:

# works, but returns list
*t_new,alt = t 
print(t_new, alt) # [1, '0076', 'AU', '9927016803A', '9927013903B', '0010'] VO

I've already tried the following, but w/o success:

tuple(*t_new),alt = t # SyntaxError
(*t_new),alt = t # still a list
(*t_new,),alt = t # ValueError

If there's no other way, I will probably go with my second attempt and cast the list to a tuple.

like image 931
Mike Scotty Avatar asked Sep 19 '25 22:09

Mike Scotty


1 Answers

why not just:

t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')

t_new, alt = t[:-1], t[-1]
print(t_new, alt)   # (1, '0076', 'AU', '9927016803A', '9927013903B', '0010') VO
like image 58
hiro protagonist Avatar answered Sep 21 '25 12:09

hiro protagonist