Compare list element to input numbers in python - python

I am working on a python exercise and here is the question:
Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
This is the original list:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
I have the following code:
b = list()
num = raw_input('Give me a number: ')
for i in a:
if i < num:
b.append(i)
print b
But no matter what number I entered it always returns all numbers from the original list into the new list.
Any suggestion or comment?

You need to cast your input to an int, otherwise you are going to be comparing int to str. Change your input prompt to:
num = int(raw_input('Give me a number: '))

Related

Is there a function to ask for input till a value is in a particular list?

Is there a way to ask for an input till the input is in the four options given for e.g.
list = [1, 2, 3, 4]
number = input('number: ')
In this example, I want it to input till the number is not in the list.
I know we can do it like this
list = [1, 2, 3, 4]
while True:
number = input('Number: ')
if number in list:
break
else:
pass
But, I want a shorter code as it is too tedious if there are multiple inputs.
The shorter but practically the same code would be:
number=0
while number not in list:
number = int(nput('Number: '))
Though please do not name the variable list as it is already a keyword
You don't need the else/pass and you need to cast the input to integer
list = [1, 2, 3, 4]
while True:
number = int(input("give number"))
if number in list:
break
print(number)

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"

How to fill an empty list with values from user input?

Okay, so I am at ground level in python, currently trying to do the following:
I want to create a list of numbers received from user input, so for example I have an empty list and when prompted I type 4 and script returns me a list containing 4 items like 0, 1, 2, 3, if i type in 8 it will return 0, 1, 2, 3, 4, 5, 6, 7 and so on.
So far, after numerous attempts I came up with the following code:
x = input("Please enter a number: ")
numbers = []
for i in range(int(x)):
numbers.append(i)
print(numbers)
It kinda works, but not really, it doesn't do exactly what I wanted:
Please enter a number: 4
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
Process finished with exit code 0
And I want it to return this :
Please enter a number: 4
[0, 1, 2, 3]
Given my current proficiency in python I have no clue how to work around it.
Many thanks in advance for your help :)
Simply move the print function out of the loop:
x = input("Please enter a number: ")
numbers = []
for i in range(int(x)):
numbers.append(i)
print(numbers)
list=[]
num=int(input("Enter the number you wanna insert:")
for i in range(num):
x=int(input("Enter Number:")
list.append(x)

Reading in a list python [duplicate]

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()

How to replace a value in a list

the program asks user to enter 5 unique number, if the number is already in the list, ask for a new number. after 5 unique numbers have been entered, display the list
numbers = ['1','2','3','4','5']
count = 0
index = 0
while count <6:
user = raw_input ("Enter a number: ")
if user in numbers:
print "not unique"
if user not in numbers:
print "unique"
count += 1
numbers = numbers.replace(index,user)
index +=1
print numbers
when the program gets to the replace method, it raise an attribute error
You can use:
numbers[index] = user
A list doesn't have a replace() method. A string does have a replace method however.
If you wish to append a number to the end of a list, you can use append():
numbers.append(user)
If you wish to insert a number at a given position, you can use insert() (for example, position 0):
numbers.insert(0, user)
You don't have to initialize a list in Python:
numbers = []
while len(numbers) != 5:
num = raw_input('Enter a number: ')
if num not in numbers:
numbers.append(num)
else:
print('{} is already added'.format(num))
print(numbers)
You can replace it with Subscript notation, like this
numbers[index] = user
Apart from that your program can be improved, like this
numbers = []
while len(numbers) < 5:
user = raw_input ("Enter a number: ")
if user in numbers:
print "not unique"
else:
print "unique"
numbers.append(user)
print numbers
If you don't care about the order of the numbers, you should probably look into sets. Addidionally, if you want to work with numbers, not strings, you should cast the string to an int. I would've written something like this.
nums = set()
while len(nums) < 5:
try:
nums.add(int(raw_input("Enter a number: ")))
except ValueError:
print 'That is not a number!'
print 'Numbers entered: {}'.format(', '.join(str(x) for x in nums))
Output:
Enter a number: 5
Numbers entered: 5
Enter a number: 3
Numbers entered: 3, 5
Enter a number: 1
Numbers entered: 1, 3, 5
Enter a number: 7
Numbers entered: 1, 3, 5, 7
Enter a number: 9
Numbers entered: 1, 3, 9, 5, 7

Categories