DrDeceptive
DrDeceptive

Reputation: 33

Is there a way to turn an input into a list?

I am trying to make an average calculator so that you can input as many numbers as you like and I am trying to turn an input into a list, how can I do this? Here is my code that I have so far.

numbers = []
divisor = 0
total = 0

adtonum = int(input("Enter numbers, seperated by commas (,): "))
numbers.append(adtonum)

for num in numbers:
    divisor += 1
    total = total + num
    print(num)

print("Average: ")
print(total / divisor)

Upvotes: 3

Views: 170

Answers (5)

daspartho
daspartho

Reputation: 21

You could use the eval() function here, like this-

numbers = list(eval(input("Enter numbers, seperated by commas (,): ")))

Since the input is just comma-separated numbers thus, the eval() function will evaluate it as a tuple, and then the list() function will convert it into a list.

Upvotes: 0

Hirusha Fernando
Hirusha Fernando

Reputation: 1265

Try this code.

# assign values using unpacking
divisor, total = 0, 0     

# list comprehension
numbers = [int(x) for x in input("Enter numbers, separated by commas (,): ").split(',')]

for num in numbers:
    divisor += 1
    total += num
    print(num)

print("Average: ")
print(total / divisor)

Upvotes: 1

Irfan wani
Irfan wani

Reputation: 5075

Here you go;

divisor = 0
total = 0

adtonum = (input("Enter numbers, seperated by commas (,): "))
numbers = adtonum.split(',')

for num in numbers:
    divisor += 1
    total = total + int(num)
    print(int(num))

print("Average: ")
print(total / divisor)

Explanation: As you were trying to get the input from the user but the input provided by the user couldn't be parsed into int because it contained ,. I simply got the input from the user, splited the input at commas. Note that split function returns a list of elements seperated by the character provided as the argument. Then i iterated over this list, parsed every element as int which is possible now. Rest is same.

Upvotes: 0

Shadowcoder
Shadowcoder

Reputation: 972

You can use eval function:

numbers = eval(input("Enter a list of numbers i.e; values separated by commas inside '[]' "))

Upvotes: 0

costaparas
costaparas

Reputation: 5237

Try this:

adtonum = input("Enter numbers, separated by commas (,): ")
numbers = [int(n) for n in adtonum.split(',')]

Here, we split the line up by the delimiter (in this case a comma) and use list comprehension to construct the list of numbers -- converting each of the numbers in the input string into integers one by one.

Upvotes: 6

Related Questions