Vice Chemist
Vice Chemist

Reputation: 109

Check if a list contains an element within a specific range

Through searching similar questions I've found how to use in to check if a list contains a specific element. But I wasn't able to find how to check and count if an element exists within a certain range of a list.

Example:

Inventory = [1, 2, 3, 5, 1, 2, 3, 3, 5, 0, 1, 5, 3, 6, 1, 0, 2, 4, 2, 8]

In the list there are 20 elements and 2 instances of 0. I'd like to count how many instances of zero are contained within every 5 elements with an output similar to this:

Elements 1–5 contain 0 zeroes.
Elements 6-10 contain 1 zeroes.
Elements 11-15 contain 0 zeroes.
Elements 16-20 contain 1 zeroes.

Any help is very much appreciated.

Upvotes: 0

Views: 1218

Answers (2)

Alain T.
Alain T.

Reputation: 42143

Python lists are indexed from zero (zero-based) so the indexes mentionned in your output will be artificial.

You can traverse your list in chunks of 5 using a step in the index range and a subscript from these indexes for a length of 5:

Inventory = [1, 2, 3, 5, 1, 2, 3, 3, 5, 0, 1, 5, 3, 6, 1, 0, 2, 4, 2, 8]
counts    = [(i,Inventory[i:i+5].count(0)) for i in range(0,len(Inventory),5)]

for i,count in counts:
    print(f"Elements {i+1}–{i+5} contain {count} zeroes.")

Elements 1–5 contain 0 zeroes.
Elements 6–10 contain 1 zeroes.
Elements 11–15 contain 0 zeroes.
Elements 16–20 contain 1 zeroes.

Upvotes: 1

Manusman
Manusman

Reputation: 57

You can slice the list into the range that you want and search for the element there, like so:

if element in Inventory[start:end]:
    # Do something

Upvotes: 0

Related Questions