0

I just saw some codes by others.

labels = ["{0}-{1}".format(i, i + 9) for i in range(0, 100, 10)]
print(labels)

The output is

['0-9', '10-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80-89', '90-99']

How to understand this? Are values returned at the front of the for loop?

Amir Shabani
  • 3,857
  • 6
  • 30
  • 67
Justin
  • 327
  • 3
  • 13

2 Answers2

3

This line,

labels = ["{0}-{1}".format(i, i + 9) for i in range(0, 100, 10)]

is equivalent to this code:

labels = []
for i in range(0, 100, 10):
    labels.append("{0}-{1}".format(i, i + 9))

Let's test it out:

labels = ["{0}-{1}".format(i, i + 9) for i in range(0, 100, 10)]

another_list = []
for i in range(0, 100, 10):
    another_list.append("{0}-{1}".format(i, i + 9))

print(labels == another_list)
# True

It's called List Comprehension.

Also, you have range(0, 100, 10): range is "an immutable sequence of numbers."

You can see the numbers like this:

In [1]: list(range(0, 100, 10))
Out[1]: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
Amir Shabani
  • 3,857
  • 6
  • 30
  • 67
0

First you need to understand the for loop.

for i in range(0, 100, 10) starts with i=0, and goes to i=100, in intervals of 10. So, i = [0, 10, 20, 30, 40 , 50, ..., 100].

And then the .format(i, i+9) is putting the value of i, and i+9, separeted by - in labels.