Search code examples
pythonvalueerror

Python: Receiving (ValueError: {error} not in list) while {error} is in the list in any form


I wanted to make a code which make a list containing numbers and upper cases I am too lazy so I did this

import string
List1= [string.digits+string.ascii_uppercase]

And then one of my code will separate my input into every single unit, and then make them into the list number of the list {List1}

def get_ID(NotlistNum):
  num = []
  NotlistNum = NotlistNum.upper()
  for digits in NotlistNum:
    if digits == '.':
      DotPosit = len(num)
    else:
      num.append(List1.index(digits))
  return [num, DotPosit]

And then, run this

InputID=input(‘enter your ID: ‘)
InputID=InputID.upper()
print(get_ID(InputID))

But when I run it, this happened

enter your ID: 2
Traceback (most recent call last):
  File “main.py”, line 13, in <module>
    print(get_ID(InputID))
  File “main.py”, line 10, in get_ID
    num.append(List1.index(digits))
ValueError: ‘2’ is not in list

I then tried to makeList1= [‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’+string.ascii_uppercase but same error occurs. Anyone can help me find where the problem is?


Solution

  • When you define List1 as

    List1= [string.digits+string.ascii_uppercase]
    

    your result will be ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'] it has one element and this element is this string. So actually yes, List1 doesn't contain '2'. If you want a proper list, try this:

    list_ = list(string.digits+string.ascii_uppercase)
    

    and you will have

    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    

    Update: As you still have questions, here's how the code looks like now. One thing remaining is that I don't know how you use DotPos - so I removed it, try adding it as you need.

    import string
    
    list_ = list(string.digits+string.ascii_uppercase)
    
    
    def get_id(input_id: str):
        num = []
        for digit in input_id:
            num.append(list_.index(digit))
        return [num]
    
    
    input_id = input('enter your ID: ').upper()
    
    print(get_id(input_id))