Using For in Python

Asked

Viewed 1,182 times

5

Python can only work with for' (loop) using a list?

It is not possible only with an integer as in other languages?

2 answers

5


Yes, using a data range is the idiomatic way of doing in Python and does not have the for you know in other languages. What you can do is use a while, is almost equal to for traditional.

x = 0
while x < 3:
    print(x)
    x += 1

Idiomatic form:

for x in range(0, 3):
    print(x)

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

Python has else to the for which is something useful and rare in other languages.

  • And that’s a good thing: "for" expresses loops that will surely end () while "while" expresses loops that will never finish. () as long as the "list" is not an object that implements iter(), in this case you can make "for" be an infinite loop too.

0

Complementing the answer, note that you can use range or xragne in the idiomatic form reported in the previous answer.

Using the pre-allocated range in memory all the items to be iterated, which can be a problem if the numbers are too large. In these cases it is most recommended to use xrange, which acts as a generator, allocating the objects on demand.

  • "xrange" only exists in Python 2.x - in Python 3, range already creates an object that does not create unnecessary data in memory (this is what used to be the old xrange)

Browser other questions tagged

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