How to insert a String as Integer to a List in Python - python-3.x

I need to insert a number (user input) as an integer to a Python list.
My code:
count = 0
list1 = []
for number in input():
if number != ' ':
list1.append(int(number))
Input: 10 11 12
Output: [1, 0, 1, 1, 1, 2]
Expected Output: [10, 11, 12]

Looping over a string (such as the one returned by input()) will loop over the individual characters in the string:
>>> s = 'hi guys'
>>> for char in s:
... print(char)
...
h
i
g
u
y
s
>>>
To loop over the "words" (i.e. substrings separated by spaces), you want to split() the user's input instead:
>>> s = 'hi guys'
>>> words = s.split()
>>> words
['hi', 'guys']
>>> for word in words:
... print(word)
...
hi
guys
>>>
So in your case, that would be:
for number in input().split():
list1.append(int(number))
We can leave the if number != ' ': out because split() already gets rid of all the spaces and simply returns a list of the numbers.

Here You Go
input_array = []
c_input = input('please enter the input\n')
for item in c_input.split():
input_array.append(int(item))
print (input_array)
input: - 1 11 23 23 456
Output:- [1, 11, 23, 23, 456]
i hope you find it useful

You should use split method to split the values as a list with string:
str_nums = input.split() #will give ['10','11','12']
then
lst_nums = []
for i in str_nums.split():
lst_nums.append(int(i))
print(lst_nums)
#output [10,11,12]
You can also use map and split together.
inp = "10 11 12"
print(list(map(int,inp.split(" "))))
#Output
[10,11,12]
Or
print([int(i) for i in input().split()])

Related

How to add elements of a string in a list without changing their types?

I have a string which includes str and int, for example string = "qA2". I want to add 'q', 'A' and 2 in a list but I don't want to change the type of elements. Is it possible?
You can use the .isdigit() method of the str class to do the following:
>>> s = "qA234"
>>> [int(x) if x.isdigit() else x for x in s]
['q', 'A', 2, 3, 4]
Note that this will fail for strings such as "x²" because ² (superscript 2) is considered a digit by the .isdigit() method for some reason. The following is safer:
>>> s = "3x²"
>>> [int(x) if "0" <= x <= "9" else x for x in s]
[3, 'x', '²']

How to convert list of strings to integer indexes?

I have a list like this:
lst = [['ab', 'bc', 'cd'], ['dg', 'ab']]
I want to build a string indexer and convert it into:
lst_converted = [[1,2,3], [4,1]]
Do some processing on the converted list and then if the output is [[3], [2]]
lst_output = [['cd'], ['ab']]
Here,
'ab' = 1
'bc' = 2
'cd' = 3
'dg' = 4
Strings can be arbitrary and not necessarily characters. How to do this?
Use a list comprehension along with a dictionary to map the string literals to integer values:
d = {}
d['ab'] = 1
d['bc'] = 2
d['cd'] = 3
d['dg'] = 4
lst = [['ab', 'bc', 'cd'], ['dg', 'ab']]
lst_converted = [[d[y] for y in x] for x in lst]
print(lst_converted) # [[1, 2, 3], [4, 1]]

How to take two inputs in one line separated by space in python

So I am practicing in hacker earth and I have to take two inputs in a single line separated by space.
The below code is what I used:
x, y = [x for x in input("Enter two value: ").split()]
It is supposed to take input that looks like '2 5'
And it is returning an error:
Execution failed
ValueError : not enough values to unpack (expected 2, got 1)
Stack Trace:
Traceback (most recent call last):
File "/tmp/165461120/user_code.py", line 13, in
x, y = [x for x in input("Enter two value: ").split()]
ValueError: not enough values to unpack (expected 2, got 1)
What I think I understood is that it is giving two values as a single string. If so how do I take separate them and convert them into integers?
To take two inputs
x, y = input("Enter two value: ").split()
This should do the trick. To convert to int you can do it seprately on the both x and y.
Or better way is to use a map function
x, y = map(int, input().split())
For your case, only typecasting is remaining, so that splitted numbers becomes int. So, just you have to add
x, y = [int(x) for x in input("Enter two value: ").split()]
Alternatively, For taking 2 inputs in single line, you can use map also
x, y = map(int, input().split())
This is happening because Hacker Earth, in almost all cases, gives its input line by line.
In almost all cases, the inputs are of the form below.
1
2 3 4
5
6 7 8
This will differ on problem by problem basis and needs to be personalized for each problem.
You are getting the error not enough values to unpack because Hacker Earth is giving only a single input, and you are expecting 2. If it had been more than 2, then the error would have been too many values to unpack.
In all probability its because you are trying to input the number of test cases, which is the first input, and a single number input, in most hacker earth problems.
Process-01 : using list comprehension
whole_line = input() # 1 2 3 4 5
strings = whole_line.split(' ') # ['1', '2', '3', '4', '5']
# remove extra space within numbers if any from list
numbers = [int(num) for num in strings if len(num)>0] # [1, 2, 3, 4, 5]
print(numbers) # [1, 2, 3, 4, 5]
Now you can write down the whole logic within one line like below
numbers = [ int(num) for num in input().split(' ') if len(num)>0 ]
print(numbers)
Process-02 : using filter and map function
whole_line = input() # 1 2 3 4 5
strings = whole_line.split(' ') # ['1', '2', '3', '4', '5']
# remove extra space within numbers if any from list
strings = list(filter(lambda x :len(x)>0 ,strings))
numbers = list(map(int,strings)) # convert each string to int
print(numbers) # [1, 2, 3, 4, 5]
Now you can write down the whole logic within one line like below
numbers = list(map(int,filter(lambda x : len(x)>0,input().split(' '))))
print(numbers)
In [20]: a,b = raw_input().split()
12 12.2
In [21]: a = int(a)
Out[21]: 12
In [22]: b = float(b)
Out[22]: 12.2
You can't do this in a one-liner (or at least not without some super duper extra hackz0r skills -- or semicolons), but python is not made for one-liners.

Converting string into list of every two numbers in string

A string = 1 2 3 4
Program should return = [[1,2],[3,4]]
in python
I want the string to be converted into a list of every two element from string
You could go for something very simple such as:
s = "10 2 3 4 5 6 7 8"
l = []
i = 0
list_split_str = s.split() # splitting the string according to spaces
while i < len(s) - 1:
l.append([s[i], s[i + 1]])
i += 2
This should output:
[['10', '2'], ['3', '4'], ['5', '6'], ['7', '8']]
You could also do something a little more complex like this in a two-liner:
list_split = s.split() # stripping spaces from the string
l = [[a, b] for a, b in zip(list_split[0::2], list_split[1::2])]
The slice here means that the first list starts at index zero and has a step of two and so is equal to [10, 3, 5, ...]. The second means it starts at index 1 and has a step of two and so is equal to [2, 4, 6, ...]. So we iterate over the first list for the values of a and the second for those of b.
zip returns a list of tuples of the elements of each list. In this case, [('10', '2'), ('3', '4'), ('5', '6'), ...]. It allows us to group the elements of the lists two by two and iterate over them as such.
This also works on lists with odd lengths.
For example, with s = "10 2 3 4 5 6 7 ", the above code would output:
[['10', '2'], ['3', '4'], ['5', '6']]
disregarding the 7 since it doesn't have a buddy.
here is the solution if the numbers exact length is divisible by 2
def every_two_number(number_string):
num = number_string.split(' ')
templist = []
if len(num) % 2 == 0:
for i in range(0,len(num),2):
templist.append([int(num[i]),int(num[i+1])])
return templist
print(every_two_number('1 2 3 4'))
you can remove the if condition and enclosed the code in try and except if you want your string to still be convert even if the number of your list is not divisible by 2
def every_two_number(number_string):
num = number_string.split(' ')
templist = []
try:
for i in range(0,len(num),2):
templist.append([int(num[i]),int(num[i+1])])
except:
pass
return templist
print(every_two_number('1 2 3 4 5'))

What does int(n) for n mean?

In order to put the input into a list:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Can someone explain what does 'int(n) for n in' mean?
How do I improve this question?
The entire expression is referred to as a List Comprehension. It's a simpler, Pythonic approach to construct a for loop that iterates through a list.
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
Given your code:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Lets say you run the code provided, you get a prompt for input:
Enter numbers: 10 8 25 33
Now what happens is, Python's input() function returns a string, as documented here:
https://docs.python.org/3/library/functions.html#input
So the code has now essentially become this:
numbersList = [int(n) for n in "10 8 25 33".split()]
Now the split() function returns an array of elements from a string delimited by a given character, as strings.
https://www.pythonforbeginners.com/dictionary/python-split
So now your code becomes:
numbersList = [int(n) for n in ["10", "8", "25", "33"]]
This code is now the equivalent of:
numbersAsStringsList = ["10", "8", "25", "33"]
numberList = []
for n in numbersAsStringsList:
numberList.append(int(n))
The int(n) method converts the argument n from a string to an int and returns the int.
https://docs.python.org/3/library/functions.html#int
For example input('Enter numbers: ').split() returns an array of strings like ['1', '4', '5']
int(n) for n in will loop throug the array and turn each n into an integer while n will be the respective item of the array.
let us try to understand this list comprehension expression though a simple piece of code which means the same thing.
nums = input('Enter numbers: ') # suppose 5 1 3 6
nums = nums.split() # it turns it to ['5', '1', '3', '6']
numbersList = [] # this is list in which the expression is written
for n in nums: # this will iterate in the nums.
number = int(n) # number will be converted from '5' to 5
numbersList.append(number) # add it to the list
print(numbersList) # [5, 1, 3, 6]

Resources