Using split on an input string - python

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?

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.

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

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..

Related

I want to change a variable to have no newline similar to what end='' does in print

Example Code:
list1 = [1,2,3]
for i in list1:
if i == 123:
print('E')
else:
pass
Here I want to make the variable of i = 123 and not
i =
1
2
3
Basically remove newlines
I know of the end='' used in print statements is there something like that, that can change the variable itself?
If your goal is to concatenate the list, this returns '123' as an integer:
list1 = [1,2,3]
var = [str(i) for i in list1]
new_var = ''.join(var)
num = int(new_var)
print(num)
Assuming you want to concatenate a list of digits into a single integer:
int(''.join([str(d) for d in list1]))
Taking it apart:
[str(d) for d in list1] convert all digits to their string representation
''.join(<list of strings>) concatenate list of strings into a single string (no spaces)
int(<string of digits>) convert a string of digits to an int

Converting Elements of a list without quotes (i.e. String type) to list of integer elements

I was writing some coding challenge where I was asked to take list of values as the input using STDIN and print even numbers using STDOUT
My language is Python and I wrote the following code
list1 = input()
print(list1)
#[1,2,3,4,5,6,7,8,9]
#a = [int(x) for x in input().split()]
even_nos = [num for num in a if num % 2 == 0]
print(even_nos)
it throws an error invalid literal for int base 10:'['
When I Checked for print(type(list1[2]) it shows <Class 'str'>
I tried to convert each element of list1 into integers using split() but it didn't work out
Can someone tell me how to resolve this?
even_nos=[]
for i in list1:
if i.isdigit() and int(i)%2==0:
even_nos.append(int(i))
print(even_nos)
try this..here you check for digit and if it is digit then check for even number.. if it is even you can append it to your list
in a list comprehension
even_nos=[int(num) for num in list1 if num.isdigit() if int(num)%2==0]
I assume when you were given the prompt you entered '[x,y]' instead of numbers
Also you are asking for strings which you cannot perform mathematical operations on. Instead try this
x = [int(input('enter: ')) for i in range(5)]
even = [y for y in x if y % 2 == 0]
print(even)
ini_list = ['1', '2', '3', '4'] #Just took to rephrase the input that I got in coding
val = ("[{0}]".format(', '.join(map(str, ini_list))))
print(val)
#Outputlist
#[1,2,3,4]
#The elements are in string format without quotes i.e. <class 'str'>
#This is the format I am getting as Input for the list
even_nos=[int(num) for num in val if num.isdigit() if int(num)%2==0]
print(even_nos)

Python Error. Trying to convert number into list and pull out first digit

So this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
Is giving me the TypeError: 'int' object has no attribute 'getitem'.
But if I change the 3rd line from n into i then this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(i[0])
list = lst
print list
print first_n
Gives me the list and the last number on that list. I need the first number not the last.
It gives me the first if instead I replace n in range (500): with n = raw input()
n = raw_input()
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
But this is single number and need to have run thousands of numbers. (As you can see I change the i on the 3rd line back into n)
Please can you help?
Your issue lies with the raw_input. In python 2, it returns a string, not an integer. What you need is input(), which just returns an integer:
n = input()
lst = [int(i) for i in str(n)]
first_n = int(lst[0]) #also, need lst here, not n, as it is now an integer
list = lst
print list
print first_n
Probably an easier solution here is to instead convert it to a string:
>>> str(123)[0] # Convert to string and take 1st character
'1'
If you need it as a number, you can int it back. This feels inefficient, but you're trying to solve a problem strongly related to the written representation of a number, so strings feel like the appropriate solution. You can however use solutions related to taking the place value. If you are looking for the number of hundreds in the above, for example, you could % 100. This requires a little more work to make general, though.

Remove numbers from list which contains some particular numbers in python

Given List:
l = [1,32,523,336,13525]
I am having a number 23 as an output of some particular function.
Now,
I want to remove all the numbers from list which contains either 2 or 3 or both 2 and 3.
Output should be:[1]
I want to write some cool one liner code.
Please help!
My approach was :
1.) Convert list of int into list of string.
2.) then use for loop to check for either character 2 or character 3 like this:
A=[x for x in l if "2" not in x] (not sure for how to include 3 also in this line)
3.) Convert A list into integer list using :
B= [int(numeric_string) for numeric_string in A]
This process is quiet tedious as it involves conversion to string of the number 23 as well as all the numbers of list.I want to do in integer list straight away.
You could convert the numbers to sets of characters:
>>> values = [1, 32, 523, 336, 13525]
>>> number = 23
>>> [value for value in values
... if set(str(number)).isdisjoint(set(str(value)))]
[1]
You're looking for the filter function. Say you have a list of ints and you want the odd ones only:
def is_odd(val):
return val % 2 == 1
filter(is_odd, range(100))
or a list comprehension
[x for x in range(100) if x % 2 == 1]
The list comprehension in particular is perfectly Pythonic. All you need now is a function that returns a boolean for your particular needs.

How can I use sum() function for a list in Python?

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 5 days ago.
I am doing my homework and it requirers me to use a sum () and len () functions to find the mean of an input number list, when I tried to use sum () to get the sum of the list, I got an error TypeError: unsupported operand type(s) for +: 'int' and 'str'. Following is my code:
numlist = input("Enter a list of number separated by commas: ")
numlist = numlist.split(",")
s = sum(numlist)
l = len(numlist)
m = float(s/l)
print("mean:",m)
The problem is that when you read from the input, you have a list of strings. You could do something like that as your second line:
numlist = [float(x) for x in numlist]
The problem is that you have a list of strings. You need to convert them to integers before you compute the sum. For example:
numlist = numlist.split(",")
numlist = map(int, numlist)
s = sum(numlist)
...
You are adding up strings, not numbers, which is what your error message is saying.
Convert every string into its respective integer:
numlist = map(int, numlist)
And then take the average (note that I use float() differently than you do):
arithmetic_mean = float(sum(numlist)) / len(numlist)
You want to use float() before dividing, as float(1/2) = float(0) = 0.0, which isn't what you want.
An alternative would be to just make them all float in the first place:
numlist = map(float, numlist)
Split returns you an array of strings, so you need to convert these to integers before using the sum function.
You can try this.
reduce(lambda x,y:x+y, [float(x) for x in distance])
Convert the string input to a list of float values. Here is the updated code.
numlist = list(map(int,input("Enter a list of number separated by commas: ").split(',')))
l = len(numlist)
s = sum(numlist)
print("mean :",s/l)
For Python 2.7
numlist = map(int,raw_input().split(","))
s = sum(numlist)
l = len(numlist)
m = float(s/l)
print("mean:"+ str(m))

Categories