+ 1
Want to find a element in the list
letters = ['p', 'q', ['r','z'], 's', 'p', 'u'] print(letters.index('r')) print(letters.index('p')) print(letters.index('z'))
4 Answers
+ 8
# This do the job, but may be adapted in a recursive way to support nested list of more than one level:
def findnestedindex(arr,item):
if item in arr:
return arr.index(item)
else:
for i, v in enumerate(arr):
if isinstance(v,list):
if item in v:
return (i,v.index(item))
letters = ['p', 'q', ['r','z'], 's', 'p', 'u']
print(findnestedindex(letters,'r'))
print(letters.index('p'))
print(findnestedindex(letters,'z'))
print(findnestedindex(letters,'s'))
+ 3
@Tommy L:
Appart your typo mistake ( you should decide to name the list 'letters' or 'letter' :P ), your code will produce exactly same behavior as asker code: the sub-items are not considering True that 'q' nor 'z' are in the 'letters' list... so you just make workaround to avoid a value error ^^ ( you can handle this also by catching exception )
0
ValueError: 'r' is not in list
0
if u want to find a value e.x "q", execute this code:
letters = ['p', 'q', ['r','z'], 's', 'p', 'u']
if 'q' in letter:
print("Yes, there is such an elelemnt")
else:
print("Does not exist")
-------------------------------
Try this changing 'q' for 'r', and find out what will happen :)