3

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?

joaoavf
  • 1,343
  • 1
  • 12
  • 25
  • https://stackoverflow.com/questions/12836128/convert-list-to-tuple-in-python this might help you – voiDnyx Oct 23 '17 at 14:04
  • thanks for the answer, but I can't see how it can help me. I need to be able to create a tuple that contains the whole list plus some other elements. – joaoavf Oct 23 '17 at 14:08

2 Answers2

10

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)
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

Try this:

tuple(list(a) + [b] + [c])
jurez
  • 4,436
  • 2
  • 12
  • 20