Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create nested list from two lists [duplicate]

Tags:

python

I have got two lists like this:

t = [1,2,3,4]
f = ['apples', 'oranges','grapes','pears']

I need to create a list of lists like this:

data =  [
        ['Fruit', 'Total'],
        ['apples', 1],
        ['oranges', 2],
        ['grapes', 3],
        ['pears' 4]
    ]

I have done this:

l = []
l.append(['Fruit', 'Total'])
# I guess I should have check that lists are the same size?
for i, fruit in enumerate(f):
    l.append([fruit, t[i]])

Just wondering if there is a more Pythonic way of doing this.

like image 429
smithy Avatar asked Aug 25 '26 19:08

smithy


1 Answers

Using zip and list comprehension is another way to do it. i.e., by doing l.extend([list(a) for a in zip(f, t)]):

Demo:

>>> t = [1,2,3,4]
>>> f = ['apples', 'oranges','grapes','pears']
>>> l = []
>>> l.append(['Fruit', 'Total'])
>>> l.extend([list(a) for a in zip(f, t)])
>>> l
[['Fruit', 'Total'], ['apples', 1], ['oranges', 2], ['grapes', 3], ['pears', 4]]
>>>
like image 93
shaktimaan Avatar answered Aug 28 '26 08:08

shaktimaan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!