0

I have this short piece of code I found online for converting an integer into a list of it's separated integers (like 250 becomes [2, 5, 0] etc).

  num = 213

  res = [int(x) for x in str(num)]

  print(res)

The thing is I am just thoroughly confused about how it works and was wondering if you guys could help me understand. Thank you

Hydra17
  • 103
  • 7
  • 1
    It converts a string into a list, where when it adds the items to the list it also called `int()` on each letter just right before adding them to the list. Should be pretty obvious from the `print(res)`. `213` -> `"213"` -> `[2, 1, 3]` – Torxed May 31 '20 at 12:53
  • this could alternatively be `list(map(int, str(num)))` – juanpa.arrivillaga May 31 '20 at 12:54
  • Hi. Thanks for the response. I think it's the right to left reading that's confusing me. Is that how this works. It goes from right to left instead of left to right? Also, when I remove int(x) the code doesn't work anymore? – Hydra17 May 31 '20 at 12:54
  • It's called a list comprehension, they are very useful and something you should spend some time reading about as they are used all the time to simplify looping. – Chris May 31 '20 at 12:54

0 Answers0