Search This Blog

Python: string comparison == or is

Use == when comparing values and is when comparing identities.
>>> a = 'abc'
>>> b = ''.join(['a', 'b', 'c'])
>>> a == b
True
>>> a is b
False

see also

Python: remove an item from list while iterating the list

list[:] = [item for item in list if match(item)]
The above code removes the matching items in the list without constructing a new list, therefore, the references to the list remain valid.

see also

Python: remove dictionary items while iterating it

  • Delete the matching items based on the keys:
    for k in dict.keys():
        if k == 'yes':
        del dict[k]
    
  • Delete the matching items based on the values:
    for k, v in dict.items():
        if v == 3:
            del dict[k]
    

Python: empty a list

del list[:]
list[:]=[]