Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a "for ... in" loop in Python increase space complexity?

Say I had the following function:

def findNumVowels(s):
    vowels = ['a', 'e', 'i', 'o', 'u']
    numVowels = 0
    for char in s:
        if char in vowels:
            numVowels += 1
    return numVowels

print(findNumVowels("hello world")) # 3

Would the for ... in loop add to the space complexity of this function by creating a new string for each char in s, or is this syntactic sugar that abstracts away the fact that we are accessing a specific index of a string?

like image 729
Kyle U Avatar asked Oct 20 '25 05:10

Kyle U


1 Answers

No, the loop by itself does not. Consider:

for char in some_string:
    print(char)

It only requires one extra object of constant size. This is constant with respect to the size of the string. So, it doesn't matter if my string is 10 or 1000 characters long, it always requires one extra str to loop over it. Therefore, it takes constant space.

like image 50
juanpa.arrivillaga Avatar answered Oct 21 '25 18:10

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!