0

I am writing a function that contains a list of numbers, and I need to find a way to count the occurrences of the numbers 1 and 2, only for the last 3 values of the list.

I obviously know of the .count() function, but I'm wondering if there's a way to use that only between a given index, in this case that index would be ((len(history-3), (len(history)), history being a list containing only values 1 and 2.

TL;DR: What is a way to count occurrences of values in a list between given indexes.

3 Answers3

2

As Rocky Li suggest you can get the last three elements of a list by slicing it history[-3:]. You can then use the count function on the slice to get the count of 1 and 2 in the last three spots in the list.

For example:

>>> history = [1, 2, 1, 2, 1, 2, 1, 2, 1]
>>> count_1 = history[-3:].count(1)
>>> count_2 = history[-3:].count(2)
>>> count_1
2
>>> count_2
1
lvrf
  • 188
  • 2
  • 8
1

Use negative slicing to get last n values and count using count().

lst[-3:].count(2) # counts number of 2 from last three elements of list lst.
lst[-3:].count(1) # counts number of 1 from last three elements of list lst.

List has in-built count method for counting values.

Austin
  • 25,759
  • 4
  • 25
  • 48
0

You could slice the list and then count

arr = [2,1,3,3]
arr[-3:].count(3) # 2

And you could do exactly the same with indices as indicated here

arr[start:stop].count(3)  # items start through stop-1
arr[start:].count(3)      # items start through the rest of the array
arr[:stop].count(3)       # items from the beginning through stop-1
arr[:].count(3)           # a copy of the whole array

I hope this is of any use.

Thomas Gak-Deluen
  • 2,759
  • 2
  • 28
  • 38