0

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

Jan
  • 42,290
  • 8
  • 54
  • 79
  • 1
    Look up "unpacking values", e.g. [here](https://www.pythontutorial.net/python-basics/python-unpack-list/) – Jan May 20 '23 at 23:00
  • Does this answer your question? [How are tuples unpacked in for loops?](https://stackoverflow.com/questions/10867882/how-are-tuples-unpacked-in-for-loops) – Michael M. May 20 '23 at 23:03
  • I'd even replace this with `x, y = map(float, input(...).split(","))`, because you don't actually need a list and don't use `if` clause - `map` is a bit cleaner IMO when applying a predefined/builtin function. – STerliakov May 21 '23 at 01:19

2 Answers2

2

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
tdelaney
  • 73,364
  • 6
  • 83
  • 116
1

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

coderman1234
  • 210
  • 3
  • 12