Extract tuple elements in list

Question:

my_tuples = [(1, 2, 3), (‘a’, ‘b’, ‘c’, ‘d’, ‘e’), (True, False), ‘qwerty’] For this tuple, how can I append all values in list and dictionary. For example, I want output like list1 = [1,2,3,a,b,c] so on and for dictionary I want output like{1:1,2:2,3:3,4:a}.

Thanks in advance.

For list, I tried using length of list but length is different for all tuple elements in list. So I am getting error like index out of range.
I want all elements of list of tuples as single list elements.

Asked By: Sona S

||

Answers:

Use a nested comprehension to iterate first over the tuples in my_tuples and then the items in each tuple, putting them into a single list or dictionary:

>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> [i for t in my_tuples for i in t]
[1, 2, 3, 'a', 'b', 'c', 'd', 'e', True, False, 'q', 'w', 'e', 'r', 't', 'y']
>>> {i: v for i, v in enumerate((i for t in my_tuples for i in t), 1)}
{1: 1, 2: 2, 3: 3, 4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: True, 10: False, 11: 'q', 12: 'w', 13: 'e', 14: 'r', 15: 't', 16: 'y'}

Since 'qwerty' isn’t a tuple, it’s unpacked into its individual characters (since a string is an iterable of characters, the same way that (1, 2, 3) is an iterable of ints). If that wasn’t what you were looking for, you could put it in your list of tuples as (qwerty,) to make it a one-element tuple, or you could do it inside the comprehension with an expression like (t if isinstance(t, tuple) else (t,)).

Answered By: Samwise
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.