How to make a list from user input.
![]() |
How to get create list from user input. |
Below you'll learn how to make a list from user input.
Get a list from user input with range function:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
li = [] # Empty list | |
n = False # n is False | |
while not n: # While loop till n is False | |
try: # Initiate Try/Except block | |
n = int(input('How many elements:')) # Integer input | |
except ValueError: # Catcht exception and print Error | |
print('Give another try.') | |
for k in range(0, n): # Iterate over range n | |
while n > 0: # Loop While till n is bigger than 0 | |
try: # Try/Except block to catch Exception | |
li.append(int(input('Enter your elements\n>'))) # Add to list user integer input | |
print(li) | |
n-=1 | |
except ValueError: # Print an Error if user enters no integer | |
print('wrong.Try again with number.') | |
print(f'Your list:',li) | |
How many elements:3
>1
[1]
>2
[1, 2]
>3
[1, 2, 3]
Process finished with exit code 0
Get a list from user with while loop:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
count= 0 | |
li= [] | |
while count < 5: | |
try: | |
count += 1 | |
li.append(int(input(f'Enter element for Loop {count} >> '))) | |
except ValueError: | |
print('wrong.Try again with number.') | |
print(f'List has elements {len(li)}: {li}') |
Enter element for Loop 1 >> 1
Enter element for Loop 2 >> 2
Enter element for Loop 3 >> 3
Enter element for Loop 4 >> 4
Enter element for Loop 5 >> 5
List has elements [1, 2, 3, 4, 5]
Process finished with exit code 0
Simply one liner:
Good method if we don't care what type of input we want user to enter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
li = [input('Enter 1st item:'), input('Enter 2nd item:'), input('Enter 3rd item:') ] | |
print(f'Your list elements: {li}') |
Enter 1st item:first
Enter 2nd item:second
Enter 3rd item:third
Your list elements: ['first', 'second', 'third']
Process finished with exit code 0
You
can donate me so I can afford to buy a coffee myself, this will help me
to keep going and create more content that you find interesting.
Many thanks
Stay Happy and Keep Coding :-)
Stay Happy and Keep Coding :-)
Best selling book for Python beginners:
Comments
Post a Comment