How to Take User Input for List
Take User Input for List
1.
list1 = input("Enter a list of elements separated by commas: ").split()
print("Your list is:", list1)
for i in list1:
print(i)
Output:
Enter a list of elements separated by commas: 1 2 3 4
Your list is: ['1', '2', '3', '4']
1
2
3
4
split() function is used to separate each individual element of list by space
2.
# User input for a list of integers separated by spaces
list1 = [int(x) for x in input("Enter integers for the list separated by spaces: ").split()]
# Display the resulting list
print("Your list is:", list1)
Output:
Enter integers for the list separated by spaces: 2 7 9 0 1
Your list is: [2, 7, 9, 0, 1]
3.
# User input for a list of elements separated by spaces
input_str = input("Enter elements for the list separated by spaces: ")
# Split the input string into a list of strings
list1 = input_str.split()
# Convert each element to the desired data type if needed
# Example: Convert each element to an integer
list1 = [int(element) for element in list1]
# Display the resulting list
print("Your list is:", list1)
for element in list1:
print(element)
Output:
Enter elements for the list separated by spaces: 1 2 3 4 5 6 7 8 9 11
Your list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
1
2
3
4
56
7
8
9
11
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏