1
votes

I'm a beginner to Python 3 and when I try this code it works:

a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)

Output:

Enter three digits separated by space:2 3 4
[2, 3, 4]

However I get errors when I try this:

a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)

Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

In fact this works as well:

list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)

What am I doing wrong?

3

3 Answers

4
votes

You might want to do exponentiation after converting to an int:

mylist = [int(i)**2 for i in list1]

You can't raise a string to a power (do you know what the square of the string "blah" is?), but you can raise a number to a power. So you need to convert the string to a number first.

Of course, a.split() returns a list of smaller strings derived from the original string, and you have to turn them into numbers yourself, but you already figured this out.

0
votes

Error in your code: you are trying to raise power before converting it to int

int(i**2) 
#should be 
int(i)**2

Another approach, using map function.

Syntax: map(func, iterable)

In python, String is iterable which means you can iterate over it. For example:

for i in "hello":
   print(i)

#output will be: 
    h
    e
    l
    l
    o

Another simple concept before moving to map function: split() function will return the list.

print(type("hello".split()))
#output will be
<class 'list'>

Lets use map function to answer your question:

a = map(int, input('Enter three digits separated by space:').split())

mylist = [i**2 for i in a]
print(mylist)

Explanation:

  • The input() function will ask user to enter three numbers separated by space and that will be a string, now you can use split function over the string returned by input().
  • Here, split function will return a list.
  • Now, map function comes into the picture, it will take each element from the list returned at step 2 and map it to the function, in this case, it will map each element of the list to int.
  • Variable a is map object, and map object is iterable, so you can apply for loop or list comprehension(you used list comprehension) to get desired output
-1
votes

you have to give condition for split like " " suppose the input is 2 3 4 and you want to split it as 2,3,4. and also the input return value as str so you have to change it to int as follows then you can use **

 a = input('Enter three digits separated by space:')
 b = map(int,a.split(" "))
 mylist = [i**2 for i in b]

this will work for you..