Reputation: 43
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: 1050
Reputation: 102
You can do so by joining two lists using '+' operator -
a = [1,2,3,4]
result = list(map(int, input().split())) + a
[5, 6, 7, 8, 1, 2, 3, 4]
Upvotes: 0
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
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