Faster way to change user inputs into int in a list?

Viewed 107

Currently, I have this code:

mylist = []
t1,t2 = input().split(' ')
t1 = int(t1)
t2 = int(t2)
mylist.append(t1)
mylist.append(t2)

Is there a more efficient way to do this?

2 Answers

In one line:

print([int(n) for n in input().split()])

Edit a previously created list

You can use map() and list.extend():

my_list = []
my_list.extend(map(int, input().split()))  # .split(' ') can lead to unexpected behavior
print(my_list)
# >>> 123 132542
# [123, 132542]

map(func, *iterables) –> map object

Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

This solution is resilient to multiple spaces between integers and can handle an undetermined amount of integers.

Create a new list:

my_list = list(map(int, input().split())
Related