Suraj Ajay Duvadi
Suraj Ajay Duvadi

Reputation: 43

How to append an array of space-separated integers input in an array in python?

I want to append user input of space-separated integers, as integers not array, into a formed array. Is there a way to do this?

Here is a pseudo-code:

a=[1,2,3,4]
a.append(int(input().split())
print(a)

I want it to be time-efficient, this is what I tried:

a=[1,2,3,4]
b=list(map(int, input().rstrip().split()))
a.extend(b)
print(a)

Is there a more efficient / faster way?

Expected output:

[1, 2, 3, 4, 5, 6, 7, 8]
# When input is '5 6 7 8'

Upvotes: 1

Views: 1051

Answers (3)

Apoorv Mehta
Apoorv Mehta

Reputation: 102

You can do so by joining two lists using '+' operator -

a = [1,2,3,4]
result = list(map(int, input().split())) + a

Output

[5, 6, 7, 8, 1, 2, 3, 4]

Upvotes: 0

Prabhu Teja
Prabhu Teja

Reputation: 21

You can also do it as :

a=[1,2,3,4]
b=list(map(int, input().rstrip().split()))
for i in b:
    a.append(i)
print(a)

Upvotes: 0

Anwarvic
Anwarvic

Reputation: 13022

You can do so:

a=[1,2,3,4]
a.extend(map(int, input().split()))
print(a)
#[1, 2, 3, 4, 5, 6, 7, 8]

Upvotes: 2

Related Questions