You have been building lists the long way. numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] squares = [] for n in numbers : squares . append ( n * n ) print ( squares ) Output: [ 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64 , 81 , 100 ] Four lines. A variable, a loop, an operation, an append. This works perfectly. Nothing wrong with it. But Python has a shorter way. One line instead of four. numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] squares = [ n * n for n in numbers ] print ( squares ) Out
Comment
Sign in to join the discussion.
Loading comments…