Space-separated integers to a list
It is a very common scenario while coding in Python to obtain integers from a string containing space-separated integers because the input in Python is by default in the form of a string.
Traditional way
Python3
values = input ().split() nums = [] for i in values: nums.append( int (i)) |
One Liner
Python3
nums = list ( map ( int , input ().split())) |
Here, we have taken the input using the input() function which returns a string. This string is then split about spaces to get a list of strings containing integers as strings. This list is then passed to the map function along with the int() as the function to convert the string to integers. These integer values returned are then stored as a list in variable nums
Though this one-liner is a combination of the previous ones, this list would have been incomplete without mentioning it because this is a very common use case.
10 Useful Python One Liners That Developers Must Know
Python is known for its easy-to-code and intuitive syntax. And one-liners are like the cherry on the cake which makes Python a more beautiful and beloved programming language. There are numerous features in Python Language and one of its most loved features is its one-liners. Writing Code in Python is already easy compared to other programming languages and using the one-liners makes it more easier and cool. Now let’s see what are these Python one-liners.