[Tutor] list.index() question
Alex Hall
mehgcap at gmail.com
Thu Dec 8 22:22:42 CET 2011
On 12/8/11, Robert Berman <bermanrl at cfl.rr.com> wrote:
> Hi,
>
> Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want
> to get the index of 'c'. A one dimensional list is extremely easy; val =
> list.index(value). But how do I get it for a list similar to l1. I have
> tried ind = l1[0].index('c') and that tells me 'c' is not in list.
That's right, 'c' is in l1[2], not l1[0]. Are you trying to search all
lists inside l1 for 'c' instead of a specific list inside l1?
> Either my syntax is way off or I am missing the viable solution.
>
> I am reasonably certain I could iterate over l1 until I find either the
> value or do not find the value. If that is the only way to go, could
> someone share an example of workable code to do that task reasonably well.
Maybe:
def contains(lst, val):
for i in lst:
if isinstance(i, list): return contains(i, val)
elif val==i: return True
return False
>
> Thank you for your assistance.
>
> Robert
>
--
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap
More information about the Tutor
mailing list