HazelR
HazelR

Reputation: 57

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.

Upvotes: 1

Views: 530

Answers (2)

Astik Gabani
Astik Gabani

Reputation: 605

Try below code:

output_list = []
for i in results:
    if isinstance(i, list):
        output_list.extend(i)
    else:
        output_list.append(i)

Upvotes: 3

Roy2012
Roy2012

Reputation: 12503

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]

Upvotes: 4

Related Questions