Search code examples
pythonpython-3.xlistloopsshortcut

loop right in the list | python 3


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


Solution

  • 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]