Reputation: 75
I have a list which takes n elements as input in it. Everything is fine but I want to take the input in same line separated by space. How can I modify my below code?
a = int(input("Enter size of list: "))
print("Enter elements:")
l = [int(input()) for i in range(a)]
print(l)
My output:
Enter size of list: 3
Enter elements:
1
2
3
[1, 2, 3]
I want it to look like this:
Enter size of list: 3
Enter elements:
1 2 3
[1, 2, 3]
I had tried this one (Input n elements seperated by space in python) but it didn't satisfied what I need because it's for a dynamic list but I want for a static list according to my code.
Upvotes: 3
Views: 2844
Reputation: 2540
Is something like this what you are looking for? Using enumerate()
to limit to your static value.
a = int(input("Enter size of list: "))
print("Enter elements:")
l = [int(z) for y, z in enumerate(input().split()) if y < a and z.isdigit()]
print(l)
output:
Enter size of list: 3
Enter elements:
1 2 3
[1, 2, 3]
other output:
Enter size of list: 3
Enter elements:
1 2 3 a b c 5
[1, 2, 3]
Upvotes: 4
Reputation: 49
You can use the Python map function to map given input string to int array
list(map(int , input().split()))
Upvotes: 1
Reputation: 2723
Use the string split method: https://www.w3schools.com/python/ref_string_split.asp
l = input().split(" ")
l = [int x for x in l]
Upvotes: 1