python 3 – x for x for loops – how do they work?

The reason for the apparently redundant extra mention of the variable x when writing x for x is that the first x does not need to be x. It just happens to be in the examples you give. Here are a few more examples which should clarify the difference between the first and second x in your question:

ones = [1 for x in range(10)]

This simply gives a list of 10 ones, the same as [1] * 10.

squares = [x*x for x in range(10)]

This gives x squared for each x in the specified range.

In your example, the second x is the variable used by the for loop, and the first x is simply an expression, which happens in your case to be just x. The expression can be whatever you like, and does not need to be in terms of x.


results = [expression for x in range(10)]

expression can include anything you like – a string, a calculation, a function – whatever you choose. If the expression happens to be just x then it looks unusual if you are not used to it, but it’s the same as the following:

results = []
for x in range(10):
    results.append(expression)

Leave a Comment

tech