In this tutorial, we will learn how to input a list in Python 3. Python provides several built-in methods to enter a list of values or elements from the user. Lists are one of the essential concepts in Python, and they are ordered, mutable, and can store multiple types of data.
Method 1: Using input() function with split() method
The most straightforward way to input a list in Python is to use the input() function and split() method. The input() function reads a line from the user’s input, and the split() method divides the input by the specified separator (space by default) and stores each value as a separate element in the list.
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 |
# Get the input from the user as a string input_string = input("Enter a list of numbers separated by space: ") # Use the split() method to convert the input string into a list of strings input_list = input_string.split() # Convert the list of strings to a list of integers input_list = [int(x) for x in input_list] # Print the input list print("Your list is:", input_list) |
Output
Enter a list of numbers separated by space: 1 2 3 4 5 Your list is: [1, 2, 3, 4, 5]
Method 2: Using list comprehension with input() function
Another method to input a list is by using list comprehension. List comprehension provides a concise way to create or modify lists, and it can be combined with the input() function to achieve the desired outcome.
Here’s an example using list comprehension:
1 2 3 4 5 |
# Get a list of numbers from the user and convert each element to an integer using list comprehension input_list = [int(x) for x in input("Enter a list of numbers separated by space: ").split()] # Print the input list print("Your list is:", input_list) |
Output
Enter a list of numbers separated by space: 1 2 3 4 5 Your list is: [1, 2, 3, 4, 5]
Method 3: Inputting a list with a specific number of elements
In some cases, you may want to input a list of a specific length. You can achieve this by using a for loop with the range() function to get the desired number of elements.
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Get the number of elements in the list n = int(input("Enter the number of elements in the list: ")) # Initialize an empty list input_list = [] # Use a for loop to get the input for each element for i in range(n): element = int(input(f"Enter element {i + 1}: ")) input_list.append(element) # Print the input list print("Your list is:", input_list) |
Output
Enter the number of elements in the list: 5 Enter element 1: 1 Enter element 2: 2 Enter element 3: 3 Enter element 4: 4 Enter element 5: 5 Your list is: [1, 2, 3, 4, 5]
Conclusion
Now you know how to input a list in Python 3 using various methods like input() function with split() method, list comprehension, and for loop with a specific number of elements. You can use any of these methods based on your requirements and preference. Happy coding!