Reading in a list python [duplicate] - python

This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 8 years ago.
Im writing a program that reads in a list, then displays the length of the list, and displays the list with one number displayed per line. This is what I have so far:
from List import *
def main():
numbers = eval(input("Give me an list of integers: "))
strings = ArrayToList(numbers)
length = len(strings)
print("The length of the list: ", length)
This is what Im expecting the result to be like:
Enter a list of integers: [3, [5, [1, [6, [7, None]]]]]
The length of the list:
5
The list:
3
5
1
6
7
Can anybody help me out? Im getting the length of the list to show as 2 instead of 5 which is what it should be.

Without seeing the implementation of ArrayToList, this is just a guess.
That said, I imagine your problem is that you aren't entering a list of integers, you're entering a list composed of an integer and another list... which itself is a list containing an integer and another list, all the way down. Hence len(strings) is 2, because len is not recursive.
You're could try inputting the list like [1, 2, 3, 4, 5] instead.
Alternatively, you could build your list in a loop, asking for user input for each character until an "end of input" event (of your choosing) is hit. This would let you avoid eval entirely, which is often a good idea.

def main():
numbers = input("Give me a list of space-separated integers: ").split()
print("length of the list:", len(numbers))
print("The list:", *numbers, sep='\n')
Output
In [14]: main()
Give me a list of space-separated integers: 3 5 1 6 7
length of the list: 5
The list:
3
5
1
6
7

I am assuming you are in Python3, because in Python2 you would not need the eval around input.
numbers = eval(input("Give me an list of integers: "))
length = len(numbers)
print("The length of the list: %d" % length)
print("The list: ")
for i in numbers:
print(i)
Here, you would have to enter the list in standard Python fashion though:
[1,2,3,4,5]
The equivalent in Python2 would just be a one-line change.
numbers = input("Give me an list of integers: ")

In Python 2 I would do it like this:
def main():
numbers = []
integers = []
numbers.append(raw_input("Give me an list of integers: "))
for integer in numbers[0]:
print integer
if integer.isdigit():
integers.append(integer)
print ("The length of the list: ", len(integers))
main()

Related

How to make Python choose the greatest number from 5 inputs(simple)way?

The problem is:
we write down a code
x = int(input("enter the number here"))
then we loop that 5 times with range and we want python to tell us which number is the greatest of all for example
1,10,100,1000
the greatest number is 1000
how can we do that?
I just do not know how to do it
Here is an easy approach:
nums = (input().split(','))
print(max(list(map(int, nums))))
As the input is taken as a string, when converting it to a list, the elements will be strings. The function map will convert each string in the list to an integer.
I don't know if it's exactly what you want but here is an input combined with a for loop in a range :
answers = []
for i in range(5):
x = int(input("enter the number here : "))
answers.append(x)
greatest_number = max(answers)
print("The greatest number is {}".format(greatest_number))
You can do it by splitting the input with respect to ",". After splitting the str should be turn into int using for loop. Now use max function with the new integer list to get the maximum number.
so your final code should be:
x = input("enter the number here: ")
list = x.split(",")
int_list = []
for s in list:
int_list.append(int(s))
max_num = max(int_list)

How to accept input into array and sort it?

How to accept input into array and sort it?
Good day, I am new to programming and new to Python Language.
I would like to try to code the user is asked to input 10 numbers and then display it in ascending order. I am not sure on how to make this work. Here is what I have:
print("Input 10 numbers:")
num = list(map(int, input().split()))
num.sort()
print("Element value in ascending order:")
print(*num)
But this code is list. I need to accept the input and then make it as an array and then sort it into ascending. Thanks in advance.
You can do so like this:
nums = input()
# say user inputs 1 2 3 4 ....10
nums = nums.split() # converts it to a list of strings
nums = [int(num) for num in nums] # convert them to ints
print(sorted(nums))
You can also test if the strings can be converted into ints or not to make you code more robust.

Need help getting an input from the user as a list [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 months ago.
I want to know how to take an input from the user as a list. For instance, there will be a message wanting input from the user and the user will input [1,2,3]. Then, the program will create a new variable with a type list and assign the input to that variable. (I've tried to use the enter code function but I couldn't figure it out since It's my first time asking a question so, that's why I explained my code instead of writing it)
You can use list comprehension for this. It provides a concise way to create lists. The code in the square brackets asks the user for input, splits the input into a text based list, and then converts the values in the list to integers. Unfortunately, you can't create variables unless they are explicitly written in the code.
Code
x = [int(val) for val in input("Enter your numbers: ").split()]
print(x)
Input:
Enter your numbers: 1 2 3 4 5
Output:
[1, 2, 3, 4, 5]
Additional link:
https://www.geeksforgeeks.org/python-get-a-list-as-input-from-user/
do you mean something:
inp = input("Type something")
l = [inp.split(" ")]
As far as I have understood your question, you want to make a list from the set of inputs of numbers having comma or space.
a = list(input("Enter your number: "))
b = [int(elements) for elements in a if elements not in (" ",",",'[',']')]
# Remove int if you are doing for strings
print(b)
Output:
Enter your number: [1,2,3]
[1 ,2 ,3]

How to check whether an element exists within a list? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I have tried this code of mine and it is not showing any errors also it is not showing any desired output..!!!
Code:
listx = [5, 10, 7, 4, 15, 3]
num=input("enter any number you want to search")
for i in listx :
if num not in listx : continue
else : print("Element Found",i)
You can simply use the in operator:
if int(num) in listx:
print("Element Found")
The reason your code isn't working is because the elements inside the list are integers whereas the input returns a string: "5" != 5
The num is never in the list, therefore the loop always executes continue. If you write
num=input("enter any number you want to search")
print(type(num))
and input a number, you will see num's type is returned as 'str'. To use this input as a numeric value, simply modify to
num = int(input("enter any number you want to search"))
Also you can add a failsafe, where if the user inputs a non-numeric value, the code asks for a new input.
You should typecast the input to integer value
listx = [5, 10, 7, 4, 15, 3]
num=int(input("enter any number you want to search"))
if(num in listx):
print("Element Found",i)
As I understood you want the index too!
there are two things wrong.
you used an Array List not a tuple, the code should work either way
Your input comes as a string not an integer
Here's how to fix them, will not return Index of the value
tuple = (5, 10, 7, 4, 15, 3)
num = int(input("input ? ")) # the int function makes input() an integer
if num in list: print('Found!') # you don't need a for loop here
This will return the Index of the value:
for i in range(len(tuple)):
if num not in tuple: print("Not Found"), break # for efficiency
if num == tuple[i]: print( 'Found at Index', i)
The difference between Array Lists and tuples are that tuples cannot change values, but an Array List can
this will produce an error
tuple[1] = "some value"
but this won't, given that the ArrayList variable exists
ArrayList[1] = "some value"

User input integer list [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 5 years ago.
I am trying to create a piece of code that allows me to ask the user to enter 5 numbers at once that will be stored into a list. For instance the code would would be ran and something like this would appear in the shell
Please enter five numbers separated by a single space only:
To which the user could reply like this
1 2 3 4 5
And then the numbers 1 2 3 4 5 would be stored into a list as integer values that could be called on later in the program.
Your best way of doing this, is probably going to be a list comprehension.
user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]
This will split the user's input at the spaces, and create an integer list.
You can use something like this:
my_list = input("Please enter five numbers separated by a single space only")
my_list = my_list.split(' ')
This could be achieved very easily by using the raw_input() function and then convert them to a list of string using split() and map()
num = map(int,raw_input("enter five numbers separated by a single space only" ).split())
[1, 2, 3, 4, 5]
You'll need to use regular expressions as the user may also enter non-integer values as well:
nums = [int(a) for a in re.findall(r'\d+', raw_input('Enter five integers: '))]
nums = nums if len(nums) <= 5 else nums[:5] # cut off the numbers to hold five
Here is a subtle way to take user input into a list:
l=list()
while len(l) < 5: # any range
test=input()
i=int(test)
l.append(i)
print(l)
It should be easy enough to understand. Any range range can be applied to the while loop, and simply request a number, one at a time.

Categories