Home > Enterprise >  How do I add items inside a list?
How do I add items inside a list?

Time:04-28

I am trying to write a for loop that adds the total budget of the films presented in a list.

How do I add the column of numbers in that list?

def get_records():
 film_list = []  #start of list, 
 film_list.append(['FM01', 'Stealth', 135, 80])
 film_list.append(['FM02', 'Supernova', 90, 15])
 film_list.append(['FM03', 'Robin Hood', 100, 85])
 film_list.append(['FM04', 'Rollerball', 70, 26])
 film_list.append(['FM05', 'Rust', 85, 20])
 return film_list

The first column is the id of each movie, the second is the title, and the third is the budget.

Which operator will add the budget column so that 135, 90, 100, 70, and 85 are added together?

CodePudding user response:

The integers you want to add up are at index 2 of each list. So, you can use sum() and a generator comprehension to get:

sum(item[2] for item in film_list)

to get:

480

If you must use a for loop, do the following:

total = 0
for item in film_list:
    total  = item[2]
  • Related