Search This Blog

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

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: empty a list

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

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.

python: join lists


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

list3 = list1 + list2

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 ]