Home > Blockchain >  How can i convert the loop code into the list-comprehention?
How can i convert the loop code into the list-comprehention?

Time:09-01

How can I perform List Comprehension on following Code.

records = []
for _ in range(int(input("Enter Range:"))):
    name = input('Enter Name')
    score = float(input('Enter Score'))
    records.append([name, score])
 print(records)

CodePudding user response:

Technically, not a big deal, just follow the logic:

records = [[input('Enter Name: '), 
            float(input('Enter Score: '))] 
           for _ in range(int(input("Enter Range: ")))]

However, conceptually, this expression is horrible.

CodePudding user response:

You can directly translate your existing code into a list comprehension:

records = [[input('Enter Name'), float(input('Enter Score'))]
           for _ in range(int(input('Enter Range')))]
print(records)

While that works, it's very confusing since the input at the end actually runs first, before the two input statements on the preceding line (which run once per iteration of the range). I'd not choose to write it this way, the code you already have is much easier to understand.

An interesting variation on your question might be how to do a list comprehension where you want the second input to be first in the inner 2-lists. That's actually kind of difficult to do, since we can only use expressions, not statements, to control the order the input calls get made in. I'd probably use an assignment expression (aka the "walrus operator", :=) to bind the name input to a variable, then throw away the value with some logical operators before building the inner list with the name after the score:

records = [(name := input('Enter Name')) and False or [float(input('Enter Score')), name]
           for _ in range(int(input('Enter Range')))]

There are probably other ways to do this, maybe some are cleverer than my and False or trickery.

  • Related