0

suppose in a python list:

l1 = [2,5,21,6,8,5,9,8,12]

here I want the sum of list excluding the value from 6 to 9 i.e. 2+5+21+8+12, I want the value from 6 to 9 i.e. 6,8,5,9 to get omitted.

here in the list the number 6 is at index 3 and number 9 is at index 6, so i want those values to be exclude

Want more
  • 1
  • 1
  • 1
    You need to clarify your question. Are you excluding based on index or based on entry/exit values? – Leo Sep 26 '19 at 21:02

2 Answers2

1
sum(l1) - sum(l1[l1.index(6):l1.index(9) + 1])

Note that if you had two or more occurrences of 6 or 9 in your list, this would exclude the range between the FIRST occurrences

Simon Crane
  • 2,122
  • 2
  • 10
  • 21
  • 1
    is there any way to solve the problem of two or more occurrence of 6 or 9 – Want more Sep 26 '19 at 20:54
  • You would have to specify which occurrence you wanted to be the start or end of your excluded range - see https://stackoverflow.com/questions/22267241/how-to-find-the-index-of-the-nth-time-an-item-appears-in-a-list for how to get the index in that case – Simon Crane Sep 26 '19 at 21:00
0

Assuming you need to sum all numbers in l1 but those included in [6,9], you could use list comprehension with an if for your inclusion constraint and then sum the obtained list:

sum([n for n in l1 if n not in range(6,9+1)])

drdre
  • 31
  • 4
  • 4
    The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers. From [review](https://stackoverflow.com/review). – MyNameIsCaleb Sep 27 '19 at 01:34