TransWikia.com

how to unpack list inside list and append to string in python?

Stack Overflow Asked on November 18, 2021

I have created a structure of a list:

data = [
[['name', 'date', 3] , 'text text text text'],
[['name', 'date', 5] , 'text text text text'],
[['name', 'date', 7] , 'text text text text'],
[['name', 'date', 8] , 'text text text text']
]

I want it to be just this:

data = [
['name', 'date', 3 , 'text text text text'],
['name', 'date', 5 , 'text text text text'],
['name', 'date', 7 , 'text text text text'],
['name', 'date', 8 , 'text text text text']
]

I need to unwrap the first element.

Here is code, but i want it to be done using list comprehension:

final_res = list()
for x in data:
   res = list()
   for item in x[0]:
      res.append( item)
   final_res.append(res)
   final_res.append(x[1])

I only know this function print(*list) – it just unwraps and prints out.

One Answer

use * unpacking:

data = [[*a, b] for a,b in data]

print(data)

Output:

[['name', 'date', 3, 'text text text text'],
 ['name', 'date', 5, 'text text text text'],
 ['name', 'date', 7, 'text text text text'],
 ['name', 'date', 8, 'text text text text']]

Answered by Adam.Er8 on November 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP