Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert N space separated numbers into in array in python? [closed]

Tags:

python

How do I input n integers separated by space in Python?

Suppose I want to input n elements in an array separated by space such as

3
1 2 3

In the first line we are given n and in the next line n inputs follow. How can I store them in an array?

like image 997
Harsh Avatar asked Sep 18 '14 10:09

Harsh


People also ask

How do you take a space separated array in Python?

Use input(), map() and split() function to take space-separated integer input in Python 3. You have to use list() to convert the map to a list.

How do you take n space separated integers in python?

Thanks. Easy solution is just to use the string method split. input: 5 8 0 sgshsu 123 input. split(" ") == ["5", "8", "0", "sgshsu", "123"] #Then they are easy to convert to numeric datatypes, but invalid inputs might raise errors.

How do I print numbers separated by space in Python?

To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.


1 Answers

Two ways:

  1. using input()1 and. This prompts the user to enter inputs:

    int_list = [int(x) for x in input("Enter integers:").split()]
    

    .split() separates the values in the input by spaces.

  2. using sys.argv, you can specify input from the command line

    import sys
    int_list = [int(x) for x in sys.argv[1:]]
    

1raw_input() in Python 2

like image 51
Ashoka Lella Avatar answered Nov 14 '22 23:11

Ashoka Lella