For increment in Python

Asked

Viewed 15,464 times

11

I learned that in the Python, to make a loop with for, from 1 to 10, we use the range.

Sort of like this:

for i in range(1, 10):
    print(i)

Generally, in other languages, when we require a simple increment, we use good old i++.

Example in Javascript:

for (var i; i < 10; i++){
    console.log(i);
}

I have some doubts regarding this iteration:

  1. How I would do to instead of increment I decrement?

  2. How would I do to increase that loop of twofold values, starting from 1?

  3. Is there any way to make one loop, as is usually done in other languages, such as i++?

3 answers

12


The for of Python is actually a for each. There is no for traditional with three elements where you place the beginning, end and step of "increment". But if you think about this is traditional it is just syntax sugar. A while does the same thing.

i = 1 #inicializador
while i < 10: #verifica a condição
    print(i) #o corpo, a ação
    i += 2 #o passo de "incremento"

Decrease:

i = 10 #inicializador
while i > 0: #verifica a condição
    print(i) #o corpo, a ação
    i -= 1 #o passo de "incremento"

It’s that simple.

There is a difference of using a continue since usually in a for traditional a continue will not skip the step "increment", in this construction of the while he will jump, so we need more care.

But this is not the most "pitonic" way. The use of range is always recommended as the Orion response shows. See increment 2:

for i in range(1, 10, 2):
    print(i)

Decreasing:

for i in range(10, 1, -1):
    print(i)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Intuitively the while should be faster but like the range is written at a lower level it can produce more optimized code.

  • The form with while is not faster no - is over when thinking of C in which a "range" would be a function call, with many native instructions, and i+=1 would be a single instruction - but in Python i+=1 also involves so-called methods, constant manipulation, etc...

  • for a loop with 100000 interactions, in python2 with range: 3.06ms per interaction, with while and i+=1: 8.41ms per interaction. Python3.3 with range became a little slower: 3.58ms, but much faster than while still.

  • @jsbueno makes some sense. It’s actually absurd that this happens, but these languages have these things. But what’s worth is actually measuring.

  • 1

    No, it’s not nonsense: language has an abstraction layer for you to worry about your problem, not how the computer works. This is the idea of using a very high-level lighting as Python.- We don’t even realize that it gets addicted to thinking first how the computer works on the inside - but the abstraction in this case is the builtin Range that returns an iterator - used in "for" in Python only in the small percentage of cases where someone actually wants a number and doesn’t go through a sequence of items (linash from a log file, string characters, dictionary keys)

  • Once the problem is solved algorithmically, if you need to optimize, you go after it, using profilers, and rewriting the critical parts into something that uses native code.

  • @jsbueno would be nice to have a debate about this. What you say makes sense but I still find it absurd that it is like this :) Anyway I changed the answer because it seems that it was not enough for me to say that the right thing was to do as in the reply Orion, so I put the right code to please the pitonists who want to see the "right way".

  • I really liked the face that the text was now - "intuitively the while should be faster..." became cool.

  • I’m trying to use range(1, 10, -1), but it’s not working

  • 1

    @Wallacemaxters was flawed act, if it will decrease it has to start from the highest :)

  • 1

    Let me give a moral to the @Orion response then.

Show 5 more comments

9

To decrease:

for i in range(10, 1, -1):
    print i

To increment every two:

for i in range(1, 10, 2):
    print i

To make i++ there’s no way, you’d have to use contador+=1

6

As people put in the other answers, what happens is that the for in the languages that inherited the syntax of C is just one while incremented.

In Python it is rare to actually use a for numerical in an application - why in the vast majority of cases, a for what we want is to perform a set of operations for each element of a sequence. The sequence can be elements of an array, lines of a file, records recovered from a database, letters from a string ... In other languages, in general people make a for with the variable going from 0 to the length of the sequence, and one of the first commands within the for do an assignment of the type item = sequencia[i]. In Python, the for which exists since the language was created in the 90’s is what is sometimes called for each in other languages (but not in Javascript, for each is not very consistent).

In cases where we really want to count numbers, in Python there is the call range which returns a very flexible object for counting integers, being trivial to pass parameters for countdown or 2-in-2 counts. As is what you are asking, it is better to make it clear. From 10 to 1, decreasing: for i in range(10, 0, -1): 10 is the initial parameter, 0, the end: when the value is that the interaction for, and -1 the increment. Likewise, 2 by 2: for i in range(1, 10, 2): here the count starts at 0, and increases by 2 by 2, and for when the value is 10 or higher.

Most often we need both an item in a sequence and its index number. For example, if we want to compare each letter of a string with the next, to know if they are equal:

palavra = input("Digite uma palavra: ")
total_repetidas = 0
for i, letra in enumerate(palavra):
   if i < len(palavra) - 1 and letra == palavra[i + 1]:
       total_repetidas += 1
print(f"Há um total de {total_repetidas} letras iguais em sequência em {palavra}")

Here, the so-called "enumerate" will return, for each element in the sequence contained in palavra a tuple with two elements: the first being the position of the next element, and the second the element itself. Another Python feature allows you to put two variables separated by , in the for,and the content of the tuple is associated, respectively each item for a variable.

Now this isn’t even the coolest. The coolest thing is that it’s easy to create your own calls that can be used in a for, in the same way as the range and the enumerate. It is enough that the function has the expression yield Inside: Yield works like a return partial: the function returns a value, which can be used in a for (or in other ways); when the is and runs again, the function continues running from where it was - and the next yield creates the next value. this type of function becomes a "generating function".

With this, sometimes code that is not the purpose of our main application can be written in a separate place - it can be tested independently. Suppose I want to make one for that generates the squares of the numbers instead of a linear increment:

def quadrados(n):
   for i in range(n):
      yield n * n

Ready - just that. If I want now to print all the squares of the numbers from 0 to 100 I can do:

for i in quadrados(100):
    print(i)

(as in the call of normal functions, the variables within quadrados are isolated - so I can re-use the variable i without any danger).

If I want a function that returns the Fibonacci series until the value of the series exceeds an x number:

def fibonacci(max_):
   a = 1
   b = 1
   while a < max_:
      yield a
      c = b
      b += a
      a = c

(Again, with the history of assigning multiple variables using a "," in Python it is possible to rewrite the last three lines like this:

b, a = b + a, b

how this works: first Python executes the expression on the right side. Since it has a "," it will create a tuple. Then it executes the expression in the first element of the tuple a + b and the second element - and these are the values of the temporary tuple: (a + b, b). Then, the first element of this tuple goes to variable "b" and the second to variable "a" )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.