Getting one value from a python tuple


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.

6/28/2010 8:55:35 PM

Accepted Answer

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.

6/28/2010 8:56:50 PM

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

MyTuple = (89,32)
MyTupleWithMoreValues = (1,2,3,4,5,6)

# to concatinate tuples
AnotherTuple = MyTuple + MyTupleWithMoreValues
print AnotherTuple

# it should print 89,32,1,2,3,4,5,6

# getting a value from a tuple is similar to a list
firstVal = MyTuple[0]
secondVal = MyTuple[1]

# if you have a function called MyTupleFun that returns a tuple,
# you might want to do this

# or this
v1,v2 = MyTupleFun()

Hope this clears things up further for somebody.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow