Yacer Saoud
Yacer Saoud

Reputation: 47

Trying to add new elements to a list in a loop results in only the last element

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)

Upvotes: 1

Views: 215

Answers (2)

programandoconro
programandoconro

Reputation: 2729

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

Upvotes: 3

Art
Art

Reputation: 3089

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)

Upvotes: 0

Related Questions