What is the logic of for i 'in' in python

1

I'd like to know the logic of for i in vogais , as in the example.

Doubt, does it load the entire typed word into a list in memory and already sorts according to our rankings, or does it read character by character?

For example, if you type " alguma coisa aqui ", using debug Pycharm, it already knows the amount of a , for example.

def contaVogais(caracteres):
  caracteres = caracteres.upper()
  result = 0
  vogais = 'AEIOU'

  for i in vogais:
      result += caracteres.count(i)
  return result
    
asked by anonymous 01.03.2018 / 12:32

2 answers

1

for x in variavel is the same as foreach of other languages.

  

Doubt, it loads the entire typed word into a list in memory and   already sorted according to our classification, or it reads character by   character?

No, it does not sort in for , it depends on the data type, in your example you have a string variable, so when you use the for i in vogais syntax it is only looping in each string letter .

  

For example, if you type: "something here", using debug pycharm,   he already knows the amount of letters to, for example.

This happens because you are using the count method inside the loop to count how many times a character appears in the string caracteres.count(i) where i represents the letter you want to know how many times it has occurred.

    
01.03.2018 / 12:52
1

In this case you do not have any typing, but you can have it elsewhere.

The for is an internally controlled loop, it knows where to start (0) and where it ends (the size of the data collection).

A string in Python is a collection of characters being that before they all have the amount of characters, then it is easy for the loop to know when to stop. It is a complete data structure. There is no magic.

The count() is one of the ways to get the amount of characters, but then it has to scan the entire string every time. This code is quadratic.

    
01.03.2018 / 12:52