Check element in list of array Python [duplicate] - python

This question already has answers here:
Check if element exists in tuple of tuples
(2 answers)
Closed 1 year ago.
I want to check if there is an element in a list of array
for example, I have:
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
So if I want to check if "horse A" is in the list. I tried:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
But if I input the horse name is : "horse B".
Input will also check every array in the list and print out the statement not found in array 1.
input:
Enter the horse name:horse B
horse B id 2 profile is not in the database. (You must enter the horse's profile before adding med records)
Enter treatment:
So how can I get rid of that ? Thank you.

You just need to move the else to be part of the for loop:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check, treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))

You need to print the "horse not found" message only after traversing all the list, not very time you find an element. And you should exit the loop after finding the correct horse, no point in iterating beyond that point. You should use for's else construct for this:
horsename_check = input("Enter horse name: ")
for i in horselist:
if i[1] == horsename_check:
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))

horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
neededHorse = "horse B"
found = 0
for horse in horselist:
if neededHorse in horse:
found = horse[0]
if found != 0:
print("Horse found in ",found)
else:
print("Horse not found!")
This should work, you can keep a condition outside the loop and check it post the loop

Related

Removing an item from the dictionary "grocery_list" causes an error

I seem to receive an error every time I try to remove an item from the dictionary. Here's my code:
print(" MY NEW AND IMPROVED GROCERY LIST ")
def grocerylist():
hist_grocery = []
grocery = True
while grocery:
choice = str(input("\n=====================\nWhat would you like to do? \n1 - Add an item\n2 - Remove an item "
"\n3 - Print entire list\n4 - Calculate cost\n5 - Exit program\nChoice: "))
if choice == "1":
print("=====================\nADD AN ITEM\n")
information = input("Give the following information: \nItem name: ")
price = input("Item price: ")
quantity = input("Item quantity: ")
grocery_list = {"Item name": str(information), "price": float(price), "quantity": int(quantity)}
hist_grocery.append(grocery_list)
** elif choice == "2":
print("=====================\nREMOVE AN ITEM\n")
remove_item = str(input("What would you like to remove? \nItem name: ")).format() # format function
grocery_list = [i for i in hist_grocery if str(i).lower() != remove_item]
**
elif choice == "3":
print("=====================\nPRINTING LIST...")
if hist_grocery == []:
print("The grocery list is empty!")
else:
[print(items, end="\t ") for items in grocery_list.values()]
Here's what I inputted: enter image description here
Tried removing the item egg but it became an error.
Here's what the terminal says:
enter image description here
I tried creating another for loop but somehow I got confused along the process. What should I change in my code?
Your error isn't with deleting an item it's with printing the items.
Since you didn't choose option 1 first there is no existing object grocery_list. I'm speculating a bit here but I assume the interpreter sees the for-each loop and assumes that it must be a list, which doesn't have a .values() method so it gives you this error.
I would try declaring an empty dictionary before your first if block.
The error has almost nothing to do with the "delete" option. The error is in the "print" option. If you look in the code for choice 2, you see that grocery_list = [i...], which is definitely a list. As the error clearly states, you cannot use .values() with a list, like when you tried to do so in the 3rd option, where [...for items in grocery_list.values()].
PS: Please don't post your error as a picture. It makes it easier for all those involved if it's typed out in the actual question.

How to accept input from an enumerated list in Python?

So I have a list that I want to number using enumerate(), then have the user choose an item from the list using the corresponding number. Is there a way to do this?
(This is broken code but hopefully, you get an idea of what I want to do)
print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = input("> ")
if userSell in enumerate(market['addresses']):
print(f"Sold {address}")
else:
print("Address not found...")
IIUC, you can use the inputted number to index your list directly:
print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = int(input("> "))-1 # you might need a loop/check here to ask again on incorrect input
try:
# assuming market['addresses'] is a list
print(f"Sold {market['addresses'][userSell]}")
except IndexError:
print("Address not found...")
It's always a good idea to validate user input - especially when you're expecting numeric values.
If you do that in this case there's no need to lookup the address after user input because you will already have validated it.
market = {'addresses': ['1 Main Road', '2 Long Street', '100 Pall Mall']}
addresses = market['addresses']
print("Which house do you want to sell?")
for number, address in enumerate(addresses, 1):
print(number, '->', address)
while True:
try:
userSell = int(input("> "))
if 0 < userSell <= len(addresses):
break
raise ValueError('Selection out of range')
except ValueError as ve:
print(ve)
print(f'Sold {addresses[userSell-1]}')
Output:
Which house do you want to sell?
1 -> 1 Main Road
2 -> 2 Long Street
3 -> 100 Pall Mall
> 2
Sold 2 Long Street
With invalid user input:
Which house do you want to sell?
1 -> 1 Main Road
2 -> 2 Long Street
3 -> 100 Pall Mall
> 0
Selection out of range
> 4
Selection out of range
> foo
invalid literal for int() with base 10: 'foo'
> 1
Sold 1 Main Road
Try changing
if userSell in enumerate(market['addresses']):
to
if userSell in range(1, len(market['addresses'])):
This will loop through the values in the range (indexes) of the addresses at the end.
To make the original code work as intended, I believe you also need to convert the user input to int type and subtract 1 because you specified start=1 when printing the options.
market= {'addresses': ["This Street", "That Street"]}
print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = int(input("> ")) - 1
if userSell in range(len(market['addresses'])):
print(f"Sold {address}")
else:
print("Address not found...")
Having to subtract 1 to make the input match the options does not feel very robust as you will have to remember to adjust the index any time you look up elements in the list later in the code. It is a good idea to store the numbered options and reference the same object later. Converting to a dict makes the code nice and readable and understandable.
market= {'addresses': ["This Street", "That Street"]}
numbered_options = dict(enumerate(market['addresses'], 1))
print("Which house do you want to sell")
for number,address in numbered_options.items():
print(number, '->', address)
userSell = int(input("> "))
if userSell in numbered_options:
print(f"Sold {numbered_options[userSell]}")
else:
print("Address not found...")
What I would really recommend, though, is using one of the many pre-built libraries for displaying lists of options and getting choices from users in the command line. You can choose from the ones mentioned in this thread and consult library documentation to implement them. No need to redo something somebody else has already done for you.

Empty lists generate no output in the context of a while and for loops

I wrote this little piece of code to practice loops and nested conditionals. My initial intention was to create two empty lists which would be progressively filled by appending the sorted input.
However, when I initialized the lists as at_risk = [] and safe = [], nothing came out as output. What did I do wrong?
When I put an element in them (quotation marks or a string), the code runs without problem.
i = 10
at_risk = []
safe = []
while i > 0:
for kids in at_risk:
question = input("Have you ever been questioned by the police, Y/N? or Q to end: ").upper()
name = input("What is your name? ")
age = int(input("How old are you?"))
if question =="Y":
at_risk.append(name)
print("This young kid", name, "is at risk.")
if age < 15:
print("These young kids", at_risk, "are at heightened risk.")
elif question == "N":
safe.append(name)
print("This kid",name," is safe.")
print("These kids",safe,"are safe.")
else:
if question == "Q":
exit(0)
The issue lies solely within these lines of code:
at_risk = []
safe = []
while i > 0:
for kids in at_risk:
You initialize your loop with for kids in at_risk, however at_risk is empty, therefor it will never begin looping. simply change at_risk and it should work!

How to keep items I enter into a List?

Each time I enter a restaurant name and then go to print the list, it does not stay inside that list. I also need to be able to use the randomize command so that Randomize() will generate a random number and use it as an index to print the restaurant at that index to the screen.
while(True):
getInput=input("Enter a restaurant name: ")
list=[]
list.append(getInput)
if(str(getInput) == "List"):
print(list)
elif(str(getInput) == "Quit"):
break;
I end up getting this:
Enter a restaurant name: Name
Enter a restaurant name: Names
Enter a restaurant name: List
['List']
Enter a restaurant name:
I need to be able to enter a restaurant and then be able to pull up that certain restaurant with a number. I just started Python a couple of months ago. Thank you!
Couple things:
You don't want to use a name like "list" because it's a function and type in Python which can make things confusing so instead name it something like "my_list".
And your issue was every loop you were starting the list from scratch. You want to move that list outside the loop instead.
my_list = []
while True:
getInput = input("Enter a restaurant name: ")
my_list.append(getInput)
if getInput == "List":
print(my_list)
elif getInput == "Quit":
break
Edit:
To answer your comment question, you can add in a number using a manual counter if you wanted (for simplicity and understandability):
my_list = []
id = 0
while True:
getInput = input("Enter a restaurant name: ")
my_list.append(f'{id}_{getInput}')
id += 1
if getInput == "List":
print(my_list)
elif getInput == "Quit":
break
You are creating a new list each time the loop repeats. Instead you should create the list before the loop even starts.

Finding and replacing in a list using user input (python)

I need help with an extra credit portion of my assignment. The objective is to make a list and then allow the user to input their own data (in this case birds) and then it sort and return the birds. The extra credit portion is to allow the user to edit any info after. I don't know how to find/replace what a user gives it.
code:
def sorted_list():
bird_list.sort()
for i in bird_list:
print(i)
print()
print('There are', len(bird_list), 'birds in the list.')
#end for
#end def
cond = 'y'
while cond == 'y':
bird = input('Type the name of another bird (RETURN when finished): ')
if bird in bird_list:
print(bird, 'is already in the list.')
else:
bird_list.append(bird)
print(bird, 'has been added to the list.')
if bird == '':
cond = 'n'
sorted_list()
#end if
#end while
edit = input('Edit? (y/n) ')
print()
if edit == 'y':
change = input('Which bird would you like to change? ')
if change == bird_list[0]:
i = input('Enter correction ' )
else:
print('Entry not found in list')
EDIT:
resolved the edit issue using this
if edit == 'y':
change = input('Which bird would you like to change? ')
if change in bird_list:
loc = bird_list.index(change)
bird_list.remove(change)
correction = input('Enter correction ' )
bird_list.insert(loc, correction)
else:
print('Entry not found in list')
First, you can use .index to find an item's position in a list.
But there is another problem in your code, which is the reason you got the 'Entry not found on list' output when you enter a name which would be at index 0 in the list, that is the first time you enter a blank string(enter the Enter key without input nothing), you append a blank string bird name in you bird_list, and your sorted_list method sort the blank string '' in the first place of the list, here:
if bird in bird_list:
print(bird, 'is already in the list.')
# if bird is ''(first time), it will be appended to the list, too
else:
bird_list.append(bird)
print(bird, 'has been added to the list.')
if bird == '':
cond = 'n'
# and this will sort '' in the 0 index of the list
sorted_list()
the correct logic should be:
if bird in bird_list:
print(bird, 'is already in the list.')
elif bird != '':
bird_list.append(bird)
print(bird, 'has been added to the list.')
else:
cond = 'n'
sorted_list()
It looks like you intend to find the position of an arbitrary bird given their name. To find an item with a specific value in a python list, use list.index. stdtypes documentation

Categories

Resources