0

I want to create a code that has the variable how many elements you take from an list and sum those. For example, if I type in 3, it takes the first 3 elements of an array and addes them together.

Preferably in some for loop but who knows what kind of creative solutions I get :)

x = [1, 3, 4, 2, 6, 9, 4]

Amount = 3

Sum = 0
Sum += x[Amount-3] + x[Amount-2] + x[Amount-1]

Desired result: 8

Amount_2 = 4

Sum = 0
Sum += x[Amount-4] + x[Amount-3] + x[Amount-2] + x[Amount-1]

Desired result: 11

Hope this explains it well.

2

1 Answer 1

1
x = [2, 6, 7, 7, 12]  # your list here
amount = int(input("Enter amount: "))
print(f'desired result: {sum(x[:amount])}')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.