flatten_sequence

sequencetools.flatten_sequence(sequence, classes=None, depth=-1, indices=None)

Flattens sequence.

Example 1. Flattens sequence completely:

>>> sequence = [1, [2, 3, [4]], 5, [6, 7, [8]]]
>>> sequencetools.flatten_sequence(sequence)
[1, 2, 3, 4, 5, 6, 7, 8]

Example 2. Flattens sequence to depth 1:

>>> sequence = [1, [2, 3, [4]], 5, [6, 7, [8]]]
>>> sequencetools.flatten_sequence(sequence, depth=1)
[1, 2, 3, [4], 5, 6, 7, [8]]

Example 3. Flattens sequence to depth 2:

>>> sequence = [1, [2, 3, [4]], 5, [6, 7, [8]]]
>>> sequencetools.flatten_sequence(sequence, depth=2)
[1, 2, 3, 4, 5, 6, 7, 8]

Example 4. Flattens sequence at indices:

>>> sequence = [0, 1, [2, 3, 4], [5, 6, 7]]
>>> sequencetools.flatten_sequence(sequence, indices=[3])
[0, 1, [2, 3, 4], 5, 6, 7]

Example 5. Flattens sequence at negative indices:

>>> sequence = [0, 1, [2, 3, 4], [5, 6, 7]]
>>> sequencetools.flatten_sequence(sequence, indices=[-1])
[0, 1, [2, 3, 4], 5, 6, 7]

Example 6. Flattens only lists in sequence:

>>> sequence = ['ab', 'cd', ['ef', 'gh'], ['ij', 'kl']]
>>> sequencetools.flatten_sequence(sequence, classes=(list,))
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

Todo

Above example only works because sequence itself is a list. Following example should produce ('ab', 'cd', 'ef', 'gh', 'ij', 'kl') but doesn’t:

>>> sequence = ('ab', 'cd', ['ef', 'gh'], ['ij', 'kl'])
>>> sequencetools.flatten_sequence(sequence, classes=(list,))
(('ab', 'cd', ['ef', 'gh'], ['ij', 'kl']),)

Leaves sequence unchanged.

Returns new object of sequence type.