35. olist — Some convenient shortcuts for common list operations.

While most of these functions look (and work) like set operations, their result differs from using Python builtin Sets in that they preserve the order of the items in the lists.

35.1. Classes defined in module olist

class olist.List(*args)[source]

A versatile list class.

This class extends the builtin list type with automatic calling of a method for all items in the list. Any method other than the ones defined here will return a new List with the method applied to each of the items, using the same arguments.

As an example, List([a,b]).len() will return List([a.len(),b.len()])

>>> L = List(['first','second'])
>>> L.upper()
>>> L.startswith('f')
[True, False]

35.2. Functions defined in module olist


Return a range as a list.

This is a convenience function for compatibility between Python2 and Python3. In Python2 the range() function returns a list, in Python3 it doesn’t. Use lrange instead of range whenever you need the whole list of numbers (thus not in a for loop).

olist.roll(a, n=1)[source]

Roll the elements of a list n positions forward (backward if n < 0)

>>> roll(lrange(5),2)
[2, 3, 4, 0, 1]
olist.union(a, b)[source]

Return a list with all items in a or in b, in the order of a,b.

>>> union(lrange(3),lrange(1,4))
[0, 1, 2, 3]
olist.difference(a, b)[source]

Return a list with all items in a but not in b, in the order of a.

>>> difference(lrange(3),lrange(1,4))
olist.symdifference(a, b)[source]

Return a list with all items in a or b but not in both.

>>> symdifference(lrange(3),lrange(1,4))
[0, 3]
olist.intersection(a, b)[source]

Return a list with all items in a and in b, in the order of a.

>>> intersection(lrange(3),lrange(1,4))
[1, 2]

Concatenate a list of lists.

>>> concatenate([lrange(3),lrange(1,4)])
[0, 1, 2, 1, 2, 3]
olist.flatten(a, recurse=False)[source]

Flatten a nested list.

By default, lists are flattened one level deep. If recurse=True, flattening recurses through all sublists.

>>> flatten([[[3.,2,],6.5,],[5],6,'hi'])
[[3.0, 2], 6.5, 5, 6, 'hi']
>>> flatten([[[3.,2,],6.5,],[5],6,'hi'],True)
[3.0, 2, 6.5, 5, 6, 'hi']
olist.group(a, n)[source]

Group a list by sequences of maximum n items.


  • a: list
  • n: integer

Returns a list of lists. Each sublist has length n, except for the last one, which may be shorter.


>>> group( [3.0, 2, 6.5, 5, 'hi'],2)
[[3.0, 2], [6.5, 5], ['hi']]
olist.select(a, b)[source]

Return a subset of items from a list.

Returns a list with the items of a for which the index is in b.

>>> select(range(2,6),[1,3])
[3, 5]
olist.remove(a, b)[source]

Returns the complement of select(a,b).

>>> remove(range(2,6),[1,3])
[2, 4]
olist.toFront(l, i)[source]

Add or move i to the front of list l

l is a list. If i is in the list, it is moved to the front of the list. Else i is added at the front of the list.

This changes the list inplace and does not return a value.

>>> L = lrange(5)
>>> toFront(L,3)
>>> L
[3, 0, 1, 2, 4]