How to combine list and individual elements into one tuple in python?

I have a few variables in python3:

a = 1
b = [2,3,4]
c = 5

I want to get a tuple which is from above variables, like: (1,2,3,4,5)

what is the easiest way to do that in python3?

4 answers

  • answered 2019-09-10 02:12 Grismar

    Creating a tuple in Python is as simple as putting the stuff you need in a tuple in parentheses:

    my_tuple = (1, 2, 3)
    a = 1
    b = 2
    c = 3
    another_tuple = (a, b, c)  # also works with variables, or anything else with a value
    

    And if what you want in the tuple is in something else that can be unpacked, like a list or a tuple itself, you can use the unpacking operator * to unpack it into the new tuple:

    a = 1
    b = [2,3,4]
    c = 5
    my_tuple = (a, *b, c)
    

    Not your question, but note that you can also get stuff from a tuple without using the * operator, as it's implied in an assignment statement:

    x, _, z = my_tuple  # continued from before
    

    In this example, what was in a (1) is now also in x and what was in c also in z. What was in b and in the second position of the tuple gets discards (that's what the underscore _ here means, "don't care".)

    You use the unpack operator in cases where you explicitly need to unpack and you're constructing some new variable, or need the elements of the tuple separately where they could also be used as a tuple. For example, when calling a function:

    a_tuple = ('Hi there', 'John')
    
    
    def greeting(phrase='Hello', name='world'):
        print(f'{phrase}, {name}!')
    
    
    greeting(*a_tuple)
    

    In this example, calling greeting as greeting(a_tuple) would give you the very nasty result of ('Hi there', 'John'), world!, clearly not what you want, but you can still use the tuple with the unpack operator.

    And the other obvious example is one like the one solving OP's question.

  • answered 2019-09-10 02:22 Rizwan Amjad

    Simply create a new tuple as shown below.

    newTuple=(a, *b, c)
    

    Note: *b unpacks list b into variables and add each variable to indexes of newTuple

  • answered 2019-09-10 02:26 Massifox

    This is the most pythonic solution:

    a = 1
    b = [2,3,4]
    c = 5
    res = a,*b,c
    # output: (1,2,3,4,5)
    

    Note: To create the new tuple, round brackets are not necessary in Python3

  • answered 2019-09-10 02:27 Gro

    One of the ways is shown below

    from functools import reduce
    import operator
    
    # create a bunch of lists, reduce them to one list and finally convert to tuple
    result = tuple(reduce(operator.add, ([a], b, [c])))
    print(result)