Search code examples
pythonlisttuplespython-itertools

convert multiple tuple into list


im working with multiple data that i read with for

for x in list_data: #i have 3 data inside
    data_file = static/upload_file/'+x

for some reason i need to pick a value from each data, i read the data using pandas dataframe, so i always append the value i want to pick from each data to a list that outside the for loop. the result i get is multiple tuple

result = [[1],[2],[3],[4],[5],[...]]

i already try using itertools like this

result = list(chain(*result))

and

final_result = []
for t in result:
        for x in t:
            final_result.append(x)

the output always like this :

[1,2,3,4,5,[1],[2],[3],[4],[5],[[1],[2],[3],[4],[5][..]]]

the output that i want is :

[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]

complete code is like this :

resul = []
final_result = []

for x in list_data: #i have 3 data inside
data_file = static/upload_file/'+x

#read_csv~
result.append((some_data))

for t in result:
    for x in t:
        final_result.append(x)

how can i convert the multiple tuple into 1 list ? thanks in advance.


Solution

  • When you add items to the final_result list, use extend rather than append. Here's the difference:

    res = [1, 2, 3]
    res.append([4, 5])
    print(res)
    
    [1, 2, 3, [4, 5]]
    
    res = [1, 2, 3]
    res.extend([2, 4])
    print(res)
    
    [1, 2, 3, 2, 4]