Prerequisites: Python Itertools
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
Itertools.groupby()
This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.
Syntax: itertools.groupby(iterable, key_func)
Parameters:
iterable: Iterable can be of any kind (list, tuple, dictionary).
key: A function that calculates keys for each element present in iterable.
Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged.
Example 1:
# Python code to demonstrate # itertools.groupby() method import itertools L = [("a", 1), ("a", 2), ("b", 3), ("b", 4)] # Key function key_func = lambda x: x[0] for key, group in itertools.groupby(L, key_func): print(key + " :", list(group)) |
Output:
a : [('a', 1), ('a', 2)]
b : [('b', 3), ('b', 4)]
Example 2 :
# Python code to demonstrate # itertools.groupby() method import itertools a_list = [("Animal", "cat"), ("Animal", "dog"), ("Bird", "peacock"), ("Bird", "pigeon")] an_iterator = itertools.groupby(a_list, lambda x : x[0]) for key, group in an_iterator: key_and_group = {key : list(group)} print(key_and_group) |
Output
{'Animal': [('Animal', 'cat'), ('Animal', 'dog')]}
{'Bird': [('Bird', 'peacock'), ('Bird', 'pigeon')]}
Recommended Posts:
- Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
- Python - Read blob object in python using wand library
- MySQL-Connector-Python module in Python
- Reading Python File-Like Objects from C | Python
- Python | PRAW - Python Reddit API Wrapper
- Important differences between Python 2.x and Python 3.x with examples
- twitter-text-python (ttp) module - Python
- Python | Convert list to Python array
- Python | Index of Non-Zero elements in Python list
- Python | Merge Python key values to list
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Visualizing O(n) using Python
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- Use of min() and max() in Python
- Python PIP
- try-except vs If in Python
- Python if else
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

