Getting one value from a tuple
Asked Answered
L

3

205

Is there a way to get one value from a tuple in Python using expressions?

def tup():
  return (3, "hello")

i = 5 + tup()  # I want to add just the three

I know I can do this:

(j, _) = tup()
i = 5 + j

But that would add a few dozen lines to my function, doubling its length.

Larousse answered 28/6, 2010 at 20:55 Comment(1)
The _ is also just a variable. It's just often used to assign value to it that can be discarded. But theoretically you can get the value from _Ambrotype
H
260

You can write

i = 5 + tup()[0]

Tuples can be indexed just like lists.

The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.

Hydraulic answered 28/6, 2010 at 20:56 Comment(0)
C
86

For anyone in the future looking for an answer, I would like to give a much clearer answer to the question.

# for making a tuple
my_tuple = (89, 32)
my_tuple_with_more_values = (1, 2, 3, 4, 5, 6)

# to concatenate tuples
another_tuple = my_tuple + my_tuple_with_more_values
print(another_tuple)
# (89, 32, 1, 2, 3, 4, 5, 6)

# getting a value from a tuple is similar to a list
first_val = my_tuple[0]
second_val = my_tuple[1]

# if you have a function called my_tuple_fun that returns a tuple,
# you might want to do this
my_tuple_fun()[0]
my_tuple_fun()[1]

# or this
v1, v2 = my_tuple_fun()

Hope this clears things up further for those that need it.

Cuda answered 1/3, 2016 at 15:8 Comment(1)
Thanks for the update. For completeness, you may want to add the use of the underscore as 'dummy' placeholder in tuple unpacking.Superman
W
9

General

Single elements of a tuple a can be accessed -in an indexed array-like fashion-

via a[0], a[1], ... depending on the number of elements in the tuple.

Example

If your tuple is a=(3,"a")

  • a[0] yields 3,
  • a[1] yields "a"

Concrete answer to question

def tup():
  return (3, "hello")

tup() returns a 2-tuple.

In order to "solve"

i = 5 + tup()  # I want to add just the three

you select the 3 by:

tup()[0]    # first element

so all together:

i = 5 + tup()[0]

Alternatives

Go with namedtuple that allows you to access tuple elements by name (and by index). Details are at https://docs.python.org/3/library/collections.html#collections.namedtuple

>>> import collections
>>> MyTuple=collections.namedtuple("MyTuple", "mynumber, mystring")
>>> m = MyTuple(3, "hello")
>>> m[0]
3
>>> m.mynumber
3
>>> m[1]
'hello'
>>> m.mystring
'hello'
Within answered 10/1, 2021 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.