Search code examples
pythonlisttuples

Remove parentheses of tuples inside a list in python


Given a list containing several tuples like this: L = [(1, 2, 3), (3, 2, 1), (2, 1, 6), (7, 3, 2), (1, 0, 2)]

I want simply to remove the parentheses of tuples and join the numbers to create a list.

The output should be like this:

L = [1, 2, 3, 3, 2, 1, 2, 1, 6, 7, 3, 2, 1, 0, 2]

I tried the below code, it removed parentheses but add a single quotation ''.

for x in L:
    mm = (', '.join(str(j) for j in x))
    L2.append(mm)
print(L2)

Like this: L = ['1, 2, 3', '3, 2, 1',' 2, 1, 6', '7, 3, 2', '1, 0, 2']


Solution

  • There are actually no parentheses or quotation marks in the data, just in the representation of the data. Your first list contains 5 tuples, your final list contains 5 strings, but your desired list contains 15 integers. Here is a simple way to accomplish what you want:

    L = [num for tup in L for num in tup]
    

    Which is basically the same as:

    new_L = []
    for tup in L:
        for num in tup:
            new_L.append(num)