How to input a list in Python? - python

Usually, we input() a list in Python 3.X like this:
x = list(map(int, input()))
print (x)
But here let's say we give an input of 1234 then it prints:`
[1, 2, 3, 4]
Is there a way that I can print it like:
[12, 34]
Thanks in Advance!

Let's say you want the numbers to be entered separated by spaces. First get the entire line as input:
line = input()
Now parse the input. In this case, split on spaces:
words = line.split(' ')
Finally, convert each "word" to an int:
numbers = [int(i) for i in words]
Of course you can use map() instead of a list comprehension.
Note that this requires input such as
12 34
You can do this all in one line, but it is better to use variables to store each intermediate step. When you get it wrong, you can debug much more easily this way.

In my opinion, I would not complicate things :
I would declare an empty list :
l = []
Then I would simply append the input :
for i in range(0, n):
print("l[", i, "] : ")
p = int(input())
l.append(p)
You can notice here the "n",it's the size for the list,in your case it would be:
for i in range(0, 1):
print("l[", i, "] : ")
p = int(input())
l.append(p)
We always start from 0,so range(0,1) would count 0, then 1 and so on with other cases.
Hope this would help.

Related

Python- Printing sequence of integers separated by commas

L=input().split(' ')
for i in L:
c=float(i)
print(int(c), sep=",")
A sequence of numbers separated by space is to be accepted from user, the numbers are converted to the greatest integer less than or equal to the number and then printed.
I wanted to print the output on same line, but my code doesn't work
Thanks in advance....
You are looping through the list, change to float and put it into variable c. That loop is essentially meaningless. After that loop c contains the last value in the iteration. Just print the result at once:
L=input().split(' ')
all_ints = map(int, L)
print(*all_ints, sep=',')
Or using str.join:
print(','.join(map(str, all_ints)))
Or using a loop:
for i in all_ints:
print(i, end=',')
To get them all as floats you can use map as well:
all_floats = list(map(float, L))
I think this should work for you:
L = input().split(' ')
for i in L:
c = float(i)
print(int(c), end=" ")

Taking single value input in Python

I was attempting to do one kata problem in Python, where I have two lists of input, let's say weight and value, which was getting input in the order (value1, weight1, value2, weight2,....)
If it were C++, I could just take one element at a time with cin to my arrays. But with Python I don't know how to take this input.
If the input is like
60 10 100 20 120 30 (in a single line)
I want my two lists val and w have values
val=[60,100,120]
w=[10,20,30]
How to take this kind of inputs in Python? Is it possible to read only one input at a time, like cin does in C++?
You can read space-separated input to a list using splitand then use slicing to get the odd/even indexed elements:
val = input().split()
val = [int(i) for i in val] #to integer
w = val[1::2] # get only odd indices
val = val[0::2] # get only even indices
print(val) # [60,100,120]
print(w) # [10,20,30]
You can then use regular indexing to get individual elements in the lists.
This should do it.
values = input("Enter values: ").split(" ")
if(len(values) % 2 != 0):
print("Error, uneven number of values and weights")
else:
val = []
w = []
for i in range(0, len(values) - 1, 2):
val.append(values[i])
w.append(values[i+1])
print("val: ", val)
print("w: ", w)
No you cannot as far as I know. input() is a function that reads one line at a time as an entire string.
A popular way to make a list out of an entire line of space separated integers is using the in-built map() function and split() method of a string object:
numbers = map(int, input.split())
numbers will now contain the list of numbers on that line.
Firstly, input() reads the entire line as a string including spaces.
split() function splits the input at space, you can also pass in a string argument to make it split anywhere you want, i.e a custom delimiter like , and creates a list of strings of those numbers
map() calls int() on each of the numbers in that list.
In C++, just like you need to know the size of input in advance, you can run a for loop on the list to now split values and weights into two lists.
val, w = [], []
for i in range(len(numbers)):
if i % 2 == 0: val.append(numbers[i])
else: w.append(numbers[i])
For better performance(relevant for large input size), you can even skip the map() step, and do something like this:
numbers = input().split()
val, w = [], []
for i in range(len(numbers)):
if i % 2 == 0: val.append(int(numbers[i]))
else: w.append(int(numbers[i]))
Here's a simple solution:
a = "60 10 100 20 120 30"
split_a = a.split(" ")
val = [e for (i, e) in enumerate(split_a) if i % 2 == 0]
w = [e for (i, e) in enumerate(split_a) if i % 2 == 1]
# or shorter with slicing (start:stop:step)
val = [e for e in split_a[0::2]]
w = [e for e in split_a[1::2]]
I am not sure what cin does but I assume the input you have is a string. One way you could do is to split it into a list of ints. And then create your val and w lists and append your values into the lists. (The first, third, fifth, etc would be your val list)
my_input_list = my_input.split(' ')
Read more here.

In Python, write a program that asks the user to type in four numbers and puts all of them in a list called lst

I've written a program that asks the user to type in four numbers like this:
a = input()
first = int(a)
b = input()
second = int(b)
c = input()
third = int(c)
d = input()
fourth = int(d)
I do not understand how can I put them in a list.
You should improve your code a little bit:
first = int(input())
second = int(input())
third = int(input())
fourth = int(input())
lst = [first, second, third, fourth]
Note that you could use list-comprehension:
lst = [int (input ()) for time in range (4)]
This uses a simple for loop to execute int (input ()) 4 times. Now you could just access the inputs by using lst [0], lst [1], 'lst [2], and lst [3].
First off, you can put your code in a code block by using an empty line and then indenting 4 spaces.
You can put your variables in a list like this:
list_variables = [first, second, third, fourth]
option one :
lst = [first, second, third, fourth]
option two :
lst = []
lst.append(first)
lst.append(second)
lst.append(third)
lst.append(fourth)
One more approach is to ask input numbers separated by space and then split them
numbers = input()
numbers_list = numbers.split(' ')
int_numbers_list = map(int, numbers_list)
Possible raise error if count of numbers not equal 4
while True:
numbers = input()
numbers_list = numbers.split(' ')
if len(numbers_list) != 4:
print('Enter numbers again')
continue
int_numbers_list = map(int, numbers_list)
break
Here is a 1-liner but does not take care of the 4 input restriction (in case you need):
lst = list(map(int, input().split()))
'''
3 4 5 6
[3, 4, 5, 6]
'''

list index out of range in simple Python script

I just started learning Python and want to create a simple script that will read integer numbers from user input and print their sum.
The code that I wrote is
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += inflow[i]
print(result)
It gives me an error
IndexError: list index out of range
pointing to result += inflow[i] line. Can't see what am I doing wrong?
BTW, is there more elegant way to split input flow to the list of integers?
You can also avoid the loop altogether:
inflow = '1 2 34 5'
Then
sum(map(int, inflow.split()))
will give the expected value
42
EDIT:
As you initialize your result with 1 and not 0, you can then also simply do:
sum(map(int, input.split()), 1)
My answer assumes that the input is always valid. If you want to catch invalid inputs, check Anton vBR's answer.
Considering: I just started learning Python
I'd suggest something like this, which handle input errors:
inflow = raw_input("Type numbers (e.g. '1 3 5') ") #in py3 input()
#inflow = '1 2 34 5'
try:
nums = map(int, inflow.split())
result = sum(nums)
print(result)
except ValueError:
print("Not a valid input")
for i in list gives the values of the list, not the index.
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += i
print(result)
If you wanted the index and not the value:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And finally, if you wanted both:
for index, value in enumerate(inflow):
script that will read integer numbers from user input and print their
sum.
try this :
inflow = list(map(int, input().split(" ")))
result = 0
for i in inflow:
result += i
print(result)
If you were going to index the list object you would do:
for i in range(len(inflow)):
result += inflow[i]
However, you are already mapping int and turning the map object into a list so thus you can just iterate over it and add up its elements:
for i in inflow:
result += i
As to your second question, since you arent doing any type testing upon cast (i.e. what happens if a user supplies 3.14159; in that case int() on a str that represents a float throws a ValueError), you can wrap it all up like so:
inflow = [int(x) for x in input().split(' ')] # input() returns `str` so just cast `int`
result = 1
for i in inflow:
result += i
print(result)
To be safe and ensure inputs are valid, I'd add a function to test type casting before building the list with the aforementioned list comprehension:
def typ(x):
try:
int(x)
return True # cast worked
except ValueError:
return False # invalid cast
inflow = [x for x in input().split(' ') in typ(x)]
result = 1
for i in inflow:
result += i
print(result)
So if a user supplies '1 2 3 4.5 5 6.3 7', inflow = [1, 2, 3, 5, 7].
What your code is doing, in chronological order, is this:
Gather user input, split per space and convert to integer, and lastly store in inflow
Initialize result to 1
Iterate over every item in inflow and set item to i
Add the current item, i to result and continue
After loop is done, print the result total.
The broken logic would be at step 4.
To answer your question, the problem is that you're not gathering the index from the list as expected-- you're iterating over each value in the list opposed to the index, so it's really undefined behavior based on what the user inputs. Though of course, it isn't what you want.
What you'd want to do is:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And on your last regard; there are two real ways to do it, one being the way you're doing right now using list, map and:
inflow = [int(v) for v in input().split()]
IMO the latter looks better. Also a suggestion; you could call stdlib function sum(<iterable>) over a list of integers or floats and it'll add each number and return the summation, which would appear more clean over a for loop.
Note: if you're splitting per whitespace you can just call the str.split() function without any parameters, as it'll split at every whitespace regardless.
>>> "hello world!".split()
['hello', 'world!']
Note: also if you want extra verification you could add a bit more logic to the list comprehension:
inflow = [int(v) for v in input().split() if v.isdigit()]
Which checks whether the user inputted valid data, and if not, skip past the data and check the following.

How do I make 'i' number of functions in python?

I'm trying to do a for loop with [i] number of similar functions in Python:
i = int(raw_input())
for i in range (0, i):
myfunction[i] = str(raw_input())
And I'm getting an error that it isn't defined. So I'm defining it.... How do I define [i] number of similar functions?
larsmans answer can also be implemented this way:
def make_function(x):
def function(y):
return x + y
return function
functions = [make_function(i) for i in xrange(5)]
# prints [4, 5, 6, 7, 8]
print [f(4) for f in functions]
Updated
From the edit and all the comments it seems that you want to ask the user for a number N and then ask for N strings and have them put into a list.
i = int(raw_input('How many? '))
strings = [raw_input('Enter: ') for j in xrange(i)]
print strings
When run:
How many? 3
Enter: a
Enter: b
Enter: c
['a', 'b', 'c']
If the list comprehension seems unreadable to you, here's how you do it without it, with some comments:
i = int(raw_input('How many? '))
# create an empty list
strings = []
# run the indented block i times
for j in xrange(i):
# ask the user for a string and append it to the list
strings.append(raw_input('Enter: '))
print strings
You can't set list items by index, try:
myfunction = []
for i in range(0, 5):
myfunction.append(whatever)
I'm not sure what you want here, but from all that you said, it appears to me to be simply this:
def myfunction(j):
for i in range(j):
variable.append(raw_input('Input something: '))
I still think this may not be what you want. Correct me if I am wrong, and please be a little clear.
myfunction[i] is the i'th element of the list myfunction, which you have not already defined; hence the error.
If you want a sequence of functions, you can try something like this:
def myfunction(i,x):
if i==0:
return sin(x)
elif i==1:
return cos(x)
elif i==2:
return x**2
else:
print 'Index outside range'
return
If you need similar functions that have something to do with i, it gets simpler, like this example:
def myfunction(i,x):
return x**i

Categories

Resources