How to unpack a single variable tuple in Python3?

Viewed 4760

I have a tuple-

('name@mail.com',).

I want to unpack it to get 'name@mail.com'.

How can I do so?

I am new to Python so please excuse.

4 Answers

The full syntax for unpacking use the syntax for tuple literal so you can use

tu = ('name@mail.com',)
(var,) = tu

The following simplified syntax is allowed

var, = tu

The prettiest way to get the first element and the last element of an iterable object like tuple, list, etc. would be to use the * feature not same as the * operator.

my_tup = ('a', 'b', 'c',)

# Last element
*other_els, last_el = my_tup

# First element
first_el, *other_els = my_tup

# You can always do index slicing similar to lists, eg [:-1], [-1] and [0], [1:]

# Cool part is since * is not greedy (meaning zero or infinite matches work) similar to regex's *. 
# This will result in no exceptions if you have only 1 element in the tuple.
my_tup = ('a',)

# This still works
# Last element
*other_els, last_el = my_tup

# First element
first_el, *other_els = my_tup

# other_els is [] here

tu = ('name@mail.com',)

str = tu[0]

print(str) #will return 'name@mail.com'

A tuple is a sequence type, which means the elements can be accessed by their indices.

A tuple is just like a list but static, so just do :

('name@mail.com',)[0]
Related