1

I am trying to match id with id_list using a one-liner,following doesnt seem to work,how do I fix it?

id  = 77bb1b03
id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']
if id in id_list:
     print "id present"
else:
     print "id not present"

4 Answers4

2

You aren't matching on equality but on a substring of the values in the list, assuming you just want to match the start:
Note: assuming id is actually a string because it isn't a valid literal.

id  = '77bb1b03'
id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']
if any(i.startswith(id) for i in id_list):
    print "id present"
else:
    print "id not present"
AChampion
  • 29,683
  • 4
  • 59
  • 75
0

First, fix your code:

id  = "77bb1b03" # needs to be a string
id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']

Then loop over the list and compare each string individually:

for s in id_list:
    if id in s:
        print "id %s present"%id
        break
else:
    print "id %s not present"%id
Jan Christoph Terasa
  • 5,781
  • 24
  • 34
0

Check this out:
Single liner as you demanded and id is a string!

>>> from __future__ import print_function
... id  = '77bb1b03'
... id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']
... [print(item, 'ID present') for item in id_list if item and item.find(id)!=-1]
77bb1b03    device ID present

Thanks @Achampion for the left -> right execution !

Devi Prasad Khatua
  • 1,185
  • 3
  • 11
  • 23
0

A nasty, obscure, slower alternative to those that will/are shown. The id var seems to prefix list items, but not sure if you would ever have need to find the id "somewhere" inside a list element.

id  = 77bb1b03
id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']
if len(filter(lambda id_list_item: id_list_item.find(id) >=0 , id_list)):
    print "id present"
else:
    print "id not present"
terryjbates
  • 312
  • 1
  • 8