I want to check if my list’s first four elements are digits. what i did is as follows:
JavaScript
x
6
1
myList = ['0', '3', '2', '7', 'O', 'K', 'P']
2
if myList[0:4] in string.digits:
3
print('okay')
4
else:
5
print('wrng')
6
But this gives the following error.
JavaScript
1
2
1
TypeError: 'in <string>' requires string as left operand, not list
2
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:
JavaScript
1
2
1
if all(ch in string.digits for ch in myList[:4]):
2
The 0
in 0:4
is not needed, it’s the default.