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.
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.
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.
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
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
('a')
is not a tuple, it resolves to 'a'
. A tuple with one element would be ('a',)
. But cool to know, *other_els, last_el = 'a'
is working also. –
Camaraderie ,
at the end. Please don't use ('a')
even if you think that you are getting the right result, it's not right. Since strings are sliceable the *rest, target
list explosion syntax works without errors. But if you use a longer string like ('abc')
this will break resulting in rest = ['a', 'b']
and target = 'c'
–
Relegate 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.
A tuple is just like a list but static, so just do :
('[email protected]',)[0]
© 2022 - 2024 — McMap. All rights reserved.
indices
to get the element.t[0]
where t is ur tuple – Caernarvonshire