Home > OS >  How to iterate through list with multiple elements in Python?
How to iterate through list with multiple elements in Python?

Time:10-07

I am trying to create sum of the list "disbursements" which works fine as per in the code. How can I iterate through/get the sum of the same list if it would look like this:

disbursements = [(2000, datetime.strptime('01-12-22', '%d-%m-%y')),
                (1000, datetime.strptime('01-12-22', '%d-%m-%y')),]

I just would like to loop through the integers 2000,1000.

def loan(principal, interest_rate):
    disbursements = [2000,1000]
    total_loan = principal   sum(disbursements)
    print(f"Total loan amount is {total_loan} EUR.")
    payback = int(total_loan   (total_loan * (interest_rate / 100)))
    print(f"Total amount to pay back is {payback} EUR.")

principal = 10000
interest_rate = 10

loan(principal, interest_rate)

CodePudding user response:

disbursements = [
    (2000, datetime.strptime('01-12-22', '%d-%m-%y')),
    (1000, datetime.strptime('01-12-22', '%d-%m-%y'))
]

So you want to loop through the first value of each tuple, right?

for amount_, date_ in disbursements:
    ... # Put here the body of the iteration

In this case I see you only need the sum of the amounts, right?

amounts_ = [amount_ for amount_, date in disbursements]
amounts = sum(amounts_)

Or, in a more coincise and efficient way:

amounts = sum(amount_ for amount_, date in disbursements)
  • Related