If I'd want to do for i in range(10): x+= 1
it obviously wouldn't work since x
is undefined, I'd have to declare x
eg x=0
before trying to write to it, but now I have two lines, one for declaring x=0
and one for actually writing the data I want to x
( for i in range(10): x+= 1
).
I was wondering, is there a way to do this in a single line? Or more specifically, declaring x
as the result of a for loop?
Something along the lines of x = for i in range(10): x+= 1
?
Would this even be possible or am I asking a nonsense question?
Not with a for
statement.
However, you can use a similar construct, such as a list comprehension expression or a generator expression:
x = sum(i for i in range(10))
which is equivalent to just saying
x = sum(range(10))
Edit: as Dougal correctly notes, in your example you increment by 1, so the equivalent is
x = sum(1 for i in range(10))
which is in turn the same as x = len(range(10))
or just x = 10
.
In most cases, i would imagine you would just want to use x
as the loop variable:
for x in range(10): pass#or range(1,11)
An enumerate
would also achieve a similar effect as what you are describing, assuming you want a different variable as the loop variable so as to do something else in the loop:
eg
for i,x in enumerate(range(x_start,x_end+1)):
#do something
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.