Iterating through list and popping number - python

I have to ask the user to input a number and if it is in the list, then I have to pop it out of the list. I am still new to Python and this is what I have so far:
Any feedback is appreciated. The problem is that the number I input is not removed and when I input a number that is not on the list, multiple "Number not found" messages print out instead of just one.
numbersList = [-11, -4, 5, 12, 13, 14, 19]
numInput = input("Enter a number: ")
for item in range(len(numbersList)):
if item == numInput:
numbersList.pop(item)
print(numbersList)
else:
print("Number not found.")

The issue is you check every element for your number, hence the reason for the multiple messages.
Simply check if the number is in the list once:
numbersList = [-11, -4, 5, 12, 13, 14, 19]
numInput = int(input("Enter a number: "))
if numInput in numbersList
numbersList.pop(numbersList.index(numInput))
print(numbersList)
else:
print("Number not found.")

You're iterating over the indexes of the array, not the values of the array.
At every iteration, if the conditional isn't met, you run the print Number not found.

numbersList = [-11, -4, 5, 12, 13, 14, 19]
numInput = input("Enter a number: ")
try:
index = numbersList.index(int(numInput))
print("Number found.")
numbersList.pop(index)
except ValueError:
print("Number not found.")

Is this good for you?
numbersList = [-11, -4, 5, 12, 13, 14, 19]
numInput = input("Enter a number: ")
if str(numInput) in str(numbersList):
numbersList.remove(numInput)
print(numInput)
else:
print("Number not found.")
You could check really quickly if an item is in a list with the in keywords.
To remove the item, just use the .remove(item_to_remove) method.

Related

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 make user input follow list in specific order

I have a code block which makes the user input Fibonacci numbers. The code block:
numb_list = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55]
numb = int(input('Enter the next Fibonacci number >'))
while numb in numb_list and numb <= 50:
numb = int(input('Enter the next Fibonacci number >'))
if numb in numb_list:
print('Well done')
else:
print('Try again')
I am asking the user to input these numbers. When the user input goes over 50 or enters all the correct numbers the program gives output 'Well done'. If user input makes a mistake the program outputs 'Try again'. This is working perfectly but how will i make the user input follow this list in this specific order and if its not in this order the program outputs 'Try again'.
This is the current output:
Enter the next Fibonacci number >1
Enter the next Fibonacci number >1
Enter the next Fibonacci number >2
Enter the next Fibonacci number >3
Enter the next Fibonacci number >8
Enter the next Fibonacci number >3
Enter the next Fibonacci number >
This is the output i would like to achieve:
Enter the next Fibonacci number >1
Enter the next Fibonacci number >1
Enter the next Fibonacci number >2
Enter the next Fibonacci number >3
Enter the next Fibonacci number >8
Enter the next Fibonacci number >3
Try again
Unfortunately I am having trouble achieving this output. Will someone be able to help me?
Thank you!
You can iterate the target number through numb_list instead and use a while loop to keep asking the user for input until the input number matches the target number:
numb_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
for target in numb_list:
while int(input('Enter the next Fibonacci number >')) != target:
print('Try again')
print('Well done')
Assuming you want to print Well done every time a correct value is entered, and that you modify your numb_list to have an extra 1 in it (As per the Fibonacci sequence), you can move through the list with an index every time you get the next value in the sequence:
numb_list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
numb = 0
current_index = 1
while numb <= 50:
numb = int(input('Enter the next Fibonacci number >'))
if numb_list[current_index] == numb:
print('Well done')
current_index += 1
else:
print('Try again')
If you dont want to print Well done every iteration, you can simply remove the print() statement

Compare list element to input numbers in 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: '))

How to search a list with user input?

So far I have...
def main():
list = [8, 25, 10, 99, 54, 3, 61, 24]
print("Your list is: ",list)
new = input("Please choose a number from the list:")
print("Your numbers index is:", list.index(new))
input("Press enter to close program")
So my issue is that I can't figure out how to take the user input and get the index of the users choice. For example, if the user entered 99, my program will return "Your numbers index is:3"
Please help.
The input function returns a string, while your list contains ints. You need to convert the string to int:
new = int(input("Please choose a number from the list: "))
I double checked the following code. Can you try running it?
def main():
list = [8, 25, 10, 99, 54, 3, 61, 24]
print("Your list is: ", list)
new = int(input("Please choose a number from the list:"))
print("Your numbers index is:", list.index(new))
input("Press enter to close program")
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