Pages

Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Sunday, December 28, 2014

Python: delete a item from a list








  • remove the first matching element:
    if e in list:
        list.remove(e)
  • remove all occurrences:
    while e in list:
        list.remove(e)
  • EAFP style: remove the first occurrence:
    try:
        list.remove(e)
    except ValueError:
        # not in the list
        pass
    
  • EAFP style: remove all occurrences:
    while True:
        try:
            list.remove(e)
        except ValueError:
            break
    

EAFP

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.




Thursday, August 28, 2014

python: join lists








list1 = ['a', 'b']
list2 = ['c', 'd']

list3 = list1 + list2



Thursday, April 17, 2014

Python: check if a list is empty








    if not a:
        print('empty')



Python: list comprehension








  • To transform a list to another:
    list2 = [ unicode(e.strip()) for e in list1 ]
    
  • To transform a list to another conditionally:
    list2 = [ unicode(e.strip()) if e is not None else '' for e in list1 ]