I love being able to assign and use multiple variables in a single expression - it looks particularly elegant. How can I repeat any arbitrary function and have my code behave as expected without using a loop? To demonstrate the integer conversion below should only use a single line.
string = '75 45 120'
v0,v1,v2 = string.split()
v0 = int(v0)
v1 = int(v1)
v2 = int(v2)
print(v0,v1,v2,v1+v2,sep=', ') # 75, 45, 120, 165
Use map
:
v0, v1, v2 = map(int, string.split())
You can use a list comprehension or generator expression if you want, but for things like this, map
can be cleaner.