How to read an array of integers from single line of input in python3

sachinjain024 picture sachinjain024 · Aug 20, 2013 · Viewed 70.2k times · Source

I want to read an array of integers from single line of input in python3. For example: Read this array to a variable/list

1 3 5 7 9

What I have tried

  1. arr = input.split(' ') But this does not convert them to integers. It creates array of strings

  2. arr = input.split(' ')

    for i,val in enumerate(arr): arr[i] = int(val)

2nd one is working for me. But I am looking for an elegant(Single line) solution.

Answer

Saullo G. P. Castro picture Saullo G. P. Castro · Aug 20, 2013

Use map:

arr = list(map(int, input().split()))

Just adding, in Python 2.x you don't need the to call list(), since map() already returns a list, but in Python 3.x "many processes that iterate over iterables return iterators themselves".

This input must be added with () i.e. parenthesis pairs to encounter the error. This works for both 3.x and 2.x Python