1

well, I am trying to understand a code of some one and the point being that he used (I guess) a lot of shortcuts in his code, I can't really understand what he is trying to do and how does it work. here is the piece of code:

scores = [int(scores_temp) for scores_temp in 
          input().strip().split(' ')]

I don't understand he makes a loop in the list? and how can he define a value (scores_temp) and just then create it in the for loop.

I really don't understands what's going on and how can I read this properly

khelwood
  • 55,782
  • 14
  • 81
  • 108
user9609349
  • 91
  • 2
  • 8
  • It's called list comprehension, as Alexander has noted. See also https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it –  Jun 21 '20 at 17:35

2 Answers2

3

Google python list comprehension and you'll get tons of material related to this. Looking at the given code, I guess the input is something like " 1 2 3 4 5 ". What you're doing inside the [] here is running a for loop and use the loop variable to create a list in one simple line

Let's break down the code. Say the input is " 1 2 3 4 5 "

input().strip()  # Strips leading and trailing spaces
>>> "1 2 3 4 5"

input().strip().split()  # Splits the string by spaces and creates a list
>>> ["1", "2", "3", "4", "5"]

Now the for loop;

for scores_temp in input().strip().split(' ')

This is now equal to

for scores_temp in ["1", "2", "3", "4", "5"]

Now the scores_temp will be equal to "1", "2", "3"... at the each loop iteration. You want to use the variable scores_temp to create a loop, normally you would do,

scores = []
for scores_temp in ["1", "2", "3", "4", "5"]:
    scores.append(int(scores_temp))  # Convert the number string to an int

Instead of the 3 lines above, in python you can use list comprehension to do this in one single line. That is what [int(scores_temp) for scores_temp in input().strip().split(' ')].

This is a very powerful tool in python. You can even use if conditions, more for loops ...etc inside []

E.g. List of even numbers up to 10

[i for i in range(10) if i%2==0]
>>> [0, 2, 4, 6, 8]
   

Flattening a list of lists

[k for j in [[1,2], [3,4]] for k in j]
>>> [1, 2, 3, 4]
Teshan Shanuka J
  • 1,448
  • 2
  • 17
  • 31
  • When you get familiar with python **dictionaries** and **generators**, you can use similar syntax with them as well. Not only lists – Teshan Shanuka J Jun 22 '20 at 10:11
2

This is called a list comprehension. It is a shortcut for creating a list. It is the same as this code:

result = []
for scores_tempo in input().strip().split():
    result.append(int(scores_temp)

Because you need to create list, dicts, sets etc. quite often python has a special shortcut syntax for this. Also known as syntactic sugar.

Alexander Kosik
  • 669
  • 3
  • 10