Chain Iterables in Python

Level 5251 keystrokes

This uses itertools to chain lists and group consecutive elements. itertools provides efficient iterator building blocks.

Python code

# Import chain and groupby from itertools
1from itertools import chain, groupby
2
# Nested list to flatten
3lists = [[1, 2], [3, 4], [5, 6]]
# chain.from_iterable flattens one level of nesting
# Converts [[1,2], [3,4], [5,6]] to [1, 2, 3, 4, 5, 6]
4flattened = list(chain.from_iterable(lists))
5print(f"Flattened: {flattened}")
6
# String with consecutive repeating characters
7data = "AAAABBBCCD"
# groupby groups consecutive identical elements
# Returns (key, group_iterator) pairs
# We count each group's length
8groups = [(k, len(list(g))) for k, g in groupby(data)]
9print(f"Groups: {groups}")

Output

Flattened: [1, 2, 3, 4, 5, 6]
Groups: [('A', 4), ('B', 3), ('C', 2), ('D', 1)]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • ,× 8
  • (× 8
  • )× 8
  • "× 6
  • [× 5
  • ]× 5
  • =× 4
  • :× 2
  • {× 2
  • }× 2

More Python examples at level 5

← Python typing practice