Dudek
Dudek

Reputation: 64

Check if Python list contains a specific element

I wrote a sample program to generate a hash code from input (it's not done yet so you don't see the part where it actually generates the hash):

import hashlib

def isInputValid(input, validInput=[]):
    for i in validInput:
        if validInput[i] == input: # error generated here
            return True
            pass
        i = i + 1
    return False
    pass

sha1hash = hashlib.sha1()
choiceValidInputs = ["1", "2"]

print ("Welcome to hash generator!\n")
print ("[1] -- generate hash from input")
print ("[2] -- quit")
choice = input("\nWhat do you want to do? ")
if not isInputValid(choice, choiceValidInputs):
    print ("Invalid option; try again")
    choice = input("What do you want to do? ")

if choice == "1":
    print ("\n[1] SHA1/SHA256")
    print ("[2] SHA512")
    hashType = input("\nWhat hash type do you want? ")
    ...
elif choice == "2":
    print ("Goodbye!")
    quit()

My Terminal window:

kali@kali:~$ python3 /home/bin/hashgenerator.py 
Welcome to hash generator!

[1] -- generate hash from input
[2] -- quit

What do you want to do? 1
Traceback (most recent call last):
  File "/home/bin/hashgenerator.py", line 19, in <module>
    if isInputValid(choice, choiceInput)==False:
  File "/home/bin/hashgenerator.py", line 5, in isInputValid
    if validInput[i] == input:
TypeError: list indices must be integers or slices, not str
kali@kali:~$ 

I want to check if the input is present in choiceValidInputs. I actually don't really know how to work with lists etc. in Python.

Thanks for helping

Upvotes: 0

Views: 73

Answers (2)

sunshineguy
sunshineguy

Reputation: 61

you're looping through elements not indexes

If you want to use indexes:

def isInputValid(input, validInput=[]):
    for i in range(len(validInput)):
        if validInput[i] == input: # error generated here
            return True

If you want to use elements you can do

def isInputValid(input, validInput=[]):
    for i in validInput:
        if i == input: # error generated here
            return True

But you can do it more easily. And more correctly :)

def isInputValid(input, validInput=[]):
    return input in validInput

Upvotes: 3

Błotosmętek
Błotosmętek

Reputation: 12927

for i in validInput:
    if validInput[i] == input:

i here is not an index of an item in validInput, it is the item itself. What you want to do is:

for i in validInput:
    if i == input:

Besides, you don't need pass and i = i+1 below. And I would suggest renaming variable input to something else to avoid confusion with input() function.

Upvotes: 1

Related Questions