How To Input A List In Python 3

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:

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:

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:

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!