Avatar ·

How does the code [i for i in range(51) if i % 2 == 0] work?

📁 List, Advanced Python Topics, AI

evens_to_50 = [i for i in range(51) if i % 2 == 0]print evens_to_50

This code generates a list of even numbers up to fifty. But as a beginner in programming, I don't understand some points:

  1. Why does the generation happen inside square brackets, which are usually used for working with indices?
  2. What does the first i before the for loop do? Why is there no colon after range(51) and no line break with indentation?
  3. Where else can square brackets be used?
  4. In square brackets with
Avatar ·

You can use range(n) to repeat something n times in Python:

for _ in range(60):    do_something()    time.sleep(1)

Is this the "correct" and "efficient" way? It depends on the specific task.

The code is simple and clear: call the do_something() function 60 times, each subsequent call occurs no earlier than one second after the previous call completes. At the end we wait one second before finishing the loop.

Imagine do_something() takes half a second on average, then the loop will take one and a half minutes or more. Is this good—to hang

Log in to leave an answer

Blogs