Getting one value from a tuple

后端 未结 2 1747
时光说笑
时光说笑 2020-11-27 03:26

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
<         


        
相关标签:
2条回答
  • 2020-11-27 03:40

    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.

    0 讨论(0)
  • 2020-11-27 03:49

    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.

    0 讨论(0)
提交回复
热议问题