+ 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'))

26th Apr 2017, 7:00 PM
nithin
nithin - avatar
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'))
26th Apr 2017, 7:31 PM
visph
visph - avatar
+ 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 )
5th May 2017, 6:59 PM
visph
visph - avatar
0
ValueError: 'r' is not in list
28th Apr 2017, 11:49 AM
Š˜Š½Š¶ŠµŠ½ŠµŃ€ ŠŸŠµŠ½Š·Š°
Š˜Š½Š¶ŠµŠ½ŠµŃ€ ŠŸŠµŠ½Š·Š° - avatar
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 :)
5th May 2017, 6:35 PM
Tommy L
Tommy L - avatar