Reputation: 10782
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.
Upvotes: 4
Views: 1818
Reputation: 1821
If you always want to have first 6 values in new tuple:
t = (1, '0076', 'AU', '9927016803A', '9927013903B', '0010', 'VO')
newT = t[0:6]
Upvotes: 1
Reputation: 46849
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
Upvotes: 7
Reputation: 40811
Either just convert it to a tuple again like you said:
*t_new, alt = t
t_new = tuple(t_new)
Or just use slicing:
t_new = t[:-1] # Will be a tuple
alt = t[-1]
If you want to talk about efficiency, tuple packing / unpacking is relatively slow when compared with slicing, so the bottom one should be the fastest.
Upvotes: 3