Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting List as Individual Elements into Tuple

I want to create a tuple from a few different elements where one of them is a list, but I want this list to be transformed into individual elements as the tuple is created.

a = range(0,10)
b = 'a'
c = 3
tuple_ex = (a,b,c)

The stored values in the tuple_ex are: ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 'a', 3)

The values I desired to be stored in the tuple_ex are: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 3)

Is there a simple way to do this or do I need to code it?

like image 428
joaoavf Avatar asked Apr 22 '26 23:04

joaoavf


1 Answers

You can use Python3's unpacking:

a = range(0,10)
b = 'a'
c = 3
t = (*a,b,c)

Output:

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 3)

For Python2:

import itertools
t = tuple(itertools.chain.from_iterable([[i] if not isinstance(i, list) else i for i in (a, b, c)]))

Output:

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 3)
like image 103
Ajax1234 Avatar answered Apr 24 '26 11:04

Ajax1234