0

How input a list in Python

2nd Oct 2020, 12:38 PM
Mohamed
Mohamed - avatar
2 Answers
+ 2
 1: Get a list of numbers as input from a user and calculate the sum of it Use a input() function to accept the list elements from a user in the format of a string separated by space. Next, Use a split() function to split a string by space and added those numbers to the list. Next, iterate a user list using for loop and range() function. Convert each list element to an integer and add it to a sum variable. input_string = input("Enter a list elements separated by space ") print("\n") userList = input_string.split() print("user list is ", userList) # Calculating the sum of input list elements sum1 = 0 for num in userList: sum1 += int(num) print("Sum = ", sum1); Output: Enter a list elements separated by space 2 4 6 8 10 12 user list is ['2', '4', '6', '8', '10', '12'] Sum = 42 i hope i helps you
2nd Oct 2020, 12:49 PM
Matias
Matias - avatar
+ 1
you could make an empty list, ask for how many items in the list, then add the items to the list in a for loop.
2nd Oct 2020, 12:46 PM
Slick
Slick - avatar