1

Lets say I had a simple python list that contained the type of expense and I wanted to iterate over these expenses with a for loop. At each iteration, if the indice produces the correct expense type a counter will be advanced by 1. I can easily write this with the code below, but it is not using a fast running for loop.

array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
sum = 0
for i in range(len(array)):
    if array[i] == 'Groceries':
        sum += 1 

Is there a more pythonic way to write this loop that accelerates the execution? I have seen examples that would look something like the code snippet below. NOTE: The code snippet below does not work, it is just an example of an accelerated format that I have seen before, but do not fully understand.

sum = [sum + 1 for i in array if array[i] == 'Groceries']

3 Answers 3

2

If it's just about counts, try collections.Counter:

from collections import Counter


array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']

counts = Counter(array)

print(counts)
# Counter({'Groceries': 2, 'Bills': 1, 'Restaurant': 1, 'Misc': 1})

print(counts['Groceries'])
# 2
Sign up to request clarification or add additional context in comments.

Comments

1
for i in range(len(array)):

is definitely NOT the Python-ic way of iterating over an array. It is VisualBasic thinking, from which you should free yourself.

If you want to iterate over an array, just iterate over it as follows:

array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
for eachItem in array:
   ...

What you do in the loop is up to you. If you want to count howmany groceries in the list, then you can do this:

array = ['Groceries', 'Restaurant', 'Groceries', 'Misc', 'Bills']
groceriesTotal = 0
for eachItem in array:
    if eachItem == 'Groceries':
         groceriesTotal = groceriesTotal + 1

This is simple, clear and pythonic enough to be readable by others.

Comments

1

You seem to think you need a list comprehension for this. But list comprehensions produce lists, and you want a scalar. Try array. count("Groceries").

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.