Python | Get a list as input from user
We often encounter a situation when we need to take number/string as input from user. In this article, we will see how to get as input a list from the user.
Examples:
Input : n = 4, ele = 1 2 3 4 Output : [1, 2, 3, 4] Input : n = 6, ele = 3 4 1 7 9 6 Output : [3, 4, 1, 7, 9, 6]
Code #1: Basic example
# creating an empty list lst = [] # number of elemetns as input n = int(input("Enter number of elements : ")) # iterating till the range for i in range(0, n): ele = int(input()) lst.append(ele) # adding the element print(lst) |
chevron_right
filter_none
Output:

Code #2: With handling exception
# try block to handle the exception try: my_list = [] while True: my_list.append(int(input())) # if input is not-integer, just print the list except: print(my_list) |
chevron_right
filter_none
Output:

Code #3: Using map()
# number of elements n = int(input("Enter number of elements : ")) # Below line read inputs from user using map() function a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n] print("\nList is - ", a) |
chevron_right
filter_none
Output:

Code #4: List of lists as input
lst = [ ] n = int(input("Enter number of elements : ")) for i in range(0, n): ele = [input(), int(input())] lst.append(ele) print(lst) |
chevron_right
filter_none
Output:

Recommended Posts:
- Take Matrix input from user in Python
- How to input multiple values from user in one line in Python?
- Python | Find all close matches of input string from a list
- User-defined Exceptions in Python with Examples
- Taking multiple inputs from user in Python
- Python | Fetch your gmail emails from a particular user
- Python | User groups with Custom permissions in Django
- Fetch top 10 starred repositories of user on GitHub | Python
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Sorting list of lists with similar list elements
- Python | Replace elements in second list with index of same element in first list
- Python | Convert list of string into sorted list of integer
- Python | Filter list of strings based on the substring list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



