tags:

views:

55

answers:

1

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.

+7  A: 

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.

David Zaslavsky
Bingo! But that drags in another question: what then is the difference between a tuple and a list? Or is there one?
BCS
tuple is immutable
Gollum
@BCS: Looks like I edited in the answer to your comment while you were writing it ;-)
David Zaslavsky