I want to check if my list’s first four elements are digits. what i did is as follows:
myList = ['0', '3', '2', '7', 'O', 'K', 'P'] if myList[0:4] in string.digits: print('okay') else: print('wrng')
But this gives the following error.
TypeError: 'in <string>' requires string as left operand, not list
How can I achieve this?
Advertisement
Answer
The error is telling you that you can’t do some_list in some_string
– after all, a list consists of characters, not lists, so it’s pointless. You want to check if all the characters in your list are in the string, so:
if all(ch in string.digits for ch in myList[:4]):
The 0
in 0:4
is not needed, it’s the default.