3

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.

smithy
  • 417
  • 1
  • 7
  • 14

2 Answers2

7

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]]
>>>
shaktimaan
  • 11,962
  • 2
  • 29
  • 33
0

Not sure I like it, but:

r = [[f[i], t[i]] if i >= 0 else ['fruit', 'total'] for i in range(-1, len(t))]
MK.
  • 33,605
  • 18
  • 74
  • 111