add a new element to a list

Viewed 105

I am trying to add elements in a list in order to identify the max float of that list. But it only appends the latest element.

mylist= [[coffee, 1, 3], [milk,2,5], [butter, 6,4]]

for items in mylist:

    value = float(items[2]) * (float(items[1]))
    values = []
    values.append(value)

Fixed thanks to @programandoconro by simply putting my values = [] outside the loop as I was resetting the list at every iteration.

2 Answers

Please try putting your values = [] outside the loop. You are resetting the list on every iteration.

Use list comprehension, something like this:

org_lst = [['coffee', 1, 3], ['milk',2,5], ['butter', 6,4]]
lst = [x[1]*x[2] for x in org_lst]
print(lst)
Related