I'm trying to understand how this line of code works but to no luck.
x, y = [float(num) for num in input("Enter a point: ").split(",")]
I did try to split this code in sections but that didn't explain how this line of code worked
I'm trying to understand how this line of code works but to no luck.
x, y = [float(num) for num in input("Enter a point: ").split(",")]
I did try to split this code in sections but that didn't explain how this line of code worked
You could break the code out as (see comments):
tmp_list = [] # create a temporary list to hold split input
point = input("Enter a point: ") # get the data
for num in point.split(","): # split string on comma then iterate
tmp_list.append(float(num)) # make a float from each value and append to list
x, y = tmp_list # unpack list to x,y. This assumes list is always len 2
del tmp_list # delete temporary list
This is a method known as list comprehension. It is used in python to shorten code that creates a list from another list. Let's go step by step.
[float(num) for num in input("Enter a point: ").split(",")]
First, we see the comprehension itself, as for num in ...
, but what is it iterating over? It iterates over an input function, split by a comma. The split method will split a string by the given seperator and return a list. This is what is being iterated over in the comprehension. The code then converts that string value into a float, before passing it on to the x and y variables by depacking the list returned
In essence, this is a lot of syntactic sugar that shortens the code in @tdelaney's answer