Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack a single variable tuple in Python3?

I have a tuple-

('[email protected]',).

I want to unpack it to get '[email protected]'.

How can I do so?

I am new to Python so please excuse.

like image 821
qazwsxedc Avatar asked Jul 01 '20 07:07

qazwsxedc


People also ask

How do you unpack a tuple in Python?

Python uses the commas ( , ) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

Is unpacking possible in a tuple?

In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.

Can you slice a Python tuple?

To index or slice a tuple you need to use the [] operator on the tuple. When indexing a tuple, if you provide a positive integer, it fetches that index from the tuple counting from the left. In case of a negative index, it fetches that index from the tuple counting from the right.


3 Answers

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

tu = ('[email protected]',)
(var,) = tu

The following simplified syntax is allowed

var, = tu
like image 171
Niko B Avatar answered Oct 19 '22 18:10

Niko B


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

like image 32
Sukhinderpal Mann Avatar answered Oct 19 '22 19:10

Sukhinderpal Mann


tu = ('[email protected]',)

str = tu[0]

print(str) #will return '[email protected]'

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

like image 2
Linosch Artox Avatar answered Oct 19 '22 20:10

Linosch Artox