-5
class Barcode:

    def __init__(self, code, code_id = None):
        self.code = code
        self.id = code_id  

I have a list of barcodes. How can I get a barcode with a specific id?

nalzok
  • 14,965
  • 21
  • 72
  • 139

1 Answers1

-1

If your BarcodeList isn't sorted, I recommend the brutal approach:

def find_item(id):
    for item in BarcodeList:
        if item.id == id:
            return item

If it is sorted, see What is the best way to get the first item from an iterable matching a condition?

PS: Why not use dict? It's born for doing this sort of job.

Community
  • 1
  • 1
nalzok
  • 14,965
  • 21
  • 72
  • 139
  • @Mitch I don't think this is an *obvious* duplicate, since the list is not necessary sorted. When it comes to the case where it's not sorted, can you provide a better approach? The brutal approach is added just for completeness. – nalzok Aug 10 '16 at 13:25
  • @Mitch Well, your answer is better, and I really think you should post an answer here. – nalzok Aug 10 '16 at 13:53
  • @Mitch You're right. Seems that answers below that question can help this OP a lot. Close vote cast. – nalzok Aug 10 '16 at 13:58