0

I have this piece of code from collections import namedtuple

Device = namedtuple('Device', ['Name', 'Timestamp'])

#add samples
deviceList = [Device(Name = "alo", Timestamp="00000"), Device(Name = "lilo", Timestamp="1111"), Device(Name = "piko", Timestamp="2222")]

def findDeviceByName(listOfDevices, DeviceName):
    print(listOfDevices)
    for x in listOfDevices:
        if (DeviceName == x.Name):
            return True
        else: 
            return False

print(findDeviceByName(deviceList, "lilo")) #returnes False even if lilo is in deviceList
print(len(deviceList)) #prints 3

and for some reason this foreach loop stops at first element in the list, but you can clearly see there are 3 elements in the list, even len() says so

not sure why this is happening, if anyone has any idea, let me know Thanks for Anwsering and Best Regards

  • 2
    You are doing a `return` that breaks the `for` loop. – Tin Nguyen Aug 14 '20 at 11:49
  • return break the loop? isn't this break; job? – TitovkaJeKapa Aug 14 '20 at 11:52
  • Given a `deviceList` is defined you can do: `any(["lilo" == device.name for device in deviceList])` to check if the device name `lilo` is present. `return` exits the method and returns the value of the method. – Tin Nguyen Aug 14 '20 at 11:53
  • why would I use "any" over a "for loop"? deviceList is only defined in testing, I am developing this as a lib and only passing it in the function – TitovkaJeKapa Aug 14 '20 at 11:58
  • `[device for device in deviceList]` is the `deviceList` itself; `[device.name == `lilo` for device in deviceList]` is a list of `True` and `False`. `any()` over a list of `True` and `False` returns True if there is a element with `True`. – Tin Nguyen Aug 14 '20 at 12:06

0 Answers0