Python extract items from tuple

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Python Tuples In python tuples are used to store immutable objects. Python Tuples are very similar to lists except to some situations. Python tuples are immutable means that they can not be modified in whole program.

    Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable. In packing, we put values into a new tuple while in unpacking we extract those values into a single variable.

    Example 1 

    Python3

    a = ("MNNIT Allahabad", 5000, "Engineering"

    (college, student, type_ofcollege) =

    print(college)

    print(student)

    print(type_ofcollege)

    Output:

    MNNIT Allahabad
    5000
    Engineering

    NOTE : In unpacking of tuple number of variables on left-hand side should be equal to number of values in given tuple a.
    Python uses a special syntax to pass optional arguments (*args) for tuple unpacking. This means that there can be many number of arguments in place of (*args) in python. All values will be assigned to every variable on the left-hand side and all remaining values will be assigned to *args .For better understanding consider the following code. 

    Example 2 

    Python3

    x, *y, z = (10, "Geeks ", " for ", "Geeks ", 50)

    print(x)

    print(y)

    print(z)

    x, y, *z = (10, "Geeks ", " for ", "Geeks ", 50)

    print(x)

    print(y)

    print(z)

    Output:

    10
    ['Geeks ', ' for ', 'Geeks ']
    50
    10
    Geeks 
    [' for ', 'Geeks ', 50]

    In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable. Consider the following code for better understanding. 

    Example 3 : 

    Python3

    def result(x, y):

        return x * y

    print (result(10, 100))

    z = (10, 100)

    print (result(*z))


    I have a tuple foo which contains something I don't care about and something I do.

    foo = (something_i_dont_need, something_i_need)
    

    Is it more correct to use

    _, x = foo
    

    or

    x = foo[1]
    

    The only things I can think of are different behaviour if foo isn't of length two. I suppose this is fairly case-specific, but is one of these the de-facto pythonic way of doing things?

    asked Feb 25, 2011 at 20:02

    2

    I've been using _ for over a decade. It is much more readable, especially when extracting more than one value:

      _, _, name, _, _, city, _ = whatever
    

    Even with only one variable, the other way forces humans readers to count if they want to truly understand the code, and more likely their eyes are just going to pass over it.

    With the underscores, you can leverage the human brain's pattern matching abilities a little better. Probably a small thing, but every little bit helps when you're debugging. :)

    answered Feb 25, 2011 at 20:09

    tangentstormtangentstorm

    7,1132 gold badges27 silver badges38 bronze badges

    I think the usual way of doing it

    x=foo[index]
    

    Using _ is less common, and I think also discouraged. Using _ is also unwieldy when you need only a few elements out of a long tuple/list. Slicing also comes handy when you are only choosing a contiguous subsequence.

    But at the end of the day I think it is just a matter of subjective preference. Use whatever that looks more readable to you and your team.

    answered Feb 25, 2011 at 20:10

    MAKMAK

    25.5k10 gold badges53 silver badges85 bronze badges

    Both are acceptable, and I've seen both in production code. I think the choice upon the context, the intent, and the local style.

    There is also a third option where the code describes the unused value:

    _real, imaginary = foo

    I use all three within my code depending upon which is clearest:

    _, x = foo

    • When the tuple is small.
    • When there are few discarded values.
    • When there are few discarded values relative to the number of extracted values.
    • The reader probably knows the tuple's composition, and the composition of the whole tuple is important.
    • When it's customary to think about the structure of the tuple as a single unit

    x=foo[i]

    • When the tuple is large.
    • When there are many discarded values for some value of many.
    • When the reader probably knows the tuple's composition.
    • The rest of the tuple's values are completely and utterly irrelevant & offer no useful information for the reader.
    • When it's customary to think about the structure as a sequence.
    • When the tuple has uniform composition.
    • When it's customary to use an index for the datatype.
    • When the index is keyed in a loop.
    • When the reader's attention should be drawn to the index's value.

    _real, imaginary = foo

    • When the tuple is small.
    • When there are few discarded values.
    • When the reader probably doesn't know the tuple's composition.
    • When naming the discarded value gives the reader insight. (You can guess from this one line that foo is a complex number.)

    answered Feb 25, 2011 at 20:49

    1

    If this is a return value from a function or method, another alternative is to write a wrapper function (or subclass the class and add a method) that returns just the item you're interested in, and calling that instead.

    answered Feb 25, 2011 at 23:23

    kindallkindall

    172k34 gold badges268 silver badges300 bronze badges

    Another possibility is to create a named tuple and use that in your return value. Then you can access the value you want by "name."

    MyTuple = collections.namedtuple('MyTuple', 'ignored needed')
    

    Then you can make

    foo = (something_i_dont_need, something_i_need)
    

    into

    foo = MyTuple(something_i_dont_need, something_i_need)
    

    and then say

    x = foo.needed
    

    instead of

    x = foo[1]
    

    Performance-wise, this may not be the best. But I think it can sometimes make writing and understanding the code easier. And it is an alternative to some of the other solutions.

    answered Dec 20, 2020 at 16:35

    Python extract items from tuple

    Gary02127Gary02127

    4,7811 gold badge23 silver badges28 bronze badges

    1st case: foo needs two variable to unpack (length of tuple is 2) . _ is perfectly ok.

    2nd case: gives you index value (slicing)

    answered Feb 25, 2011 at 20:21

    TauquirTauquir

    6,3635 gold badges35 silver badges48 bronze badges

    How do I extract data from a tuple in Python?

    In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable.

    How do you extract a tuple list?

    If it is required to extract the rear element from a list of tuples, it can be done using list comprehension and negative indexing. The list comprehension is a shorthand to iterate through the list and perform operations on it.

    How do you split a tuple object in Python?

    To split a tuple, just list the variable names separated by commas on the left-hand side of an equals sign, and then a tuple on the right-hand side.

    How do you get the second element from a tuple?

    If you need to get the second element from a list of tuples, use a list comprehension. Copied! We used a list comprehension to get a new list that contains the second element of each tuple. List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.