![]() |
VOOZH | about |
In Python, getting a list as input means a program should prompt the user to enter multiple values during execution, and these values should be captured and stored in a Python list data structure.
input()function can be combined with split()to accept multiple elements in a single line and store them in a list. The split() method separates input based on spaces and returns a list.
Example: This code takes a single line of input from the user and splits it into a list of strings.
Output
Enter elements separated by space: 1 2 3 4 5
List: ['1', '2', '3', '4', '5']
Explanation:
This method lets users add one element at a time, it is ideal when the size of the list is fixed or predefined. Here we are using a loop to repeatedly take input and append it to the list.
Example: This code uses a loop to take n inputs from the user and appends each to a list.
Output
Enter the number of elements: 3
Enter element 1: Python
Enter element 2 : is
Enter element 3: fun
List: ['Python', 'is', 'fun']
Explanation:
When your list contains numbers, you can combine split() with map() to automatically convert input to integers (or floats).
Example: This code takes a single line of numeric input, splits it and converts all elements to integers.
Output
Enter numbers separated by space: 1 2 3 4 5
List: [1, 2, 3, 4, 5]
Explanation:
List comprehension provides a compact way to create a list from user input. Combines a loop and input() into a single line for it be concise and quick.
Example: This code uses list comprehension to collect n elements from the user in a single line of code.
Output
Enter the number of elements: 3
Enter element 1: dog
Enter element 2: cat
Enter element 3: bird
List: ['dog', 'cat', 'bird']
Explanation:
A nested list is a list that contains other lists as its elements. You can take a nested list as input by splitting the input string twice: once for sublists, and once for elements within each sublist.
Example: This code takes input for a nested list using commas for elements and semicolons for sublists.
Output
Enter nested list (use commas and semicolons): 1,2,3;4,5;6,7,8
Nested List: [['1', '2', '3'], ['4', '5'], ['6', '7', '8']]
Explanation: