Python has always been a versatile language offering numerous ways to achieve a specific task. In this tutorial, we’ll explore how to take comma-separated integer input, which is a common scenario when dealing with CSV files or input data in the form of a string. We’ll implement this using different methods such as the map() function and list comprehension. So, let’s get started!
Step 1: Take User Input
In Python, to receive input from the user, we make use of the input() function. This function reads a line from input, converts it to a string, and returns it.
1 |
input_data = input("Enter the numbers separated by a comma: ") |
Step 2: Splitting the Input String
Because commas separate our integers, we’d then call the split function, which would split our string using the specified separator; comma in this case.
1 |
splitted_data = input_data.split(",") |
Step 3: Converting to Integers Using map() Function
After splitting the string, we’ll end up with a list of string numbers. To convert this list into a list of integers, we’ll use the map() function.
1 |
integer_data = list(map(int, splitted_data)) |
Step 4: Converting to Integers Using List Comprehension
Another way to convert a list of strings into integers is by using list comprehension. It provides a concise way to create lists and tends to be faster than using the map function.
1 |
integer_data = [int(num) for num in splitted_data] |
All Together
1 2 3 |
input_data = input("Enter the numbers separated by a comma: ") splitted_data = input_data.split(",") integer_data = list(map(int, splitted_data)) |
This code will output a list of integers for the provided comma-separated numbers. For example, if you enter “1,2,3,4,5” You should get:
[1, 2, 3, 4, 5]
Conclusion
Taking comma-separated integer input in Python is a simple and common task. It uses basic Python functions and concepts such as input, split, map, and list comprehension. Now, you are able to take multiple integers as input from the user in the form of a comma-separated string and convert them into a list of integers using two different methods.
Please visit the official Python documentation if you want to learn more about user input, map function, or list comprehension.