# collections और itertools — Python Fundamentals: Basics से Async तक

Source: https://www.skillbyai.com/hi/python/py-collections-itertools

> आम loops सरल बनाने के लिए Counter, defaultdict और chain व combinations जैसे itertools tools उपयोग करें।

## Counter और defaultdict

`Counter` आइटम की गिनती तुरंत करता है; `defaultdict` गुम की पर `KeyError` उठाने की बजाय एक डिफ़ॉल्ट मान देता है।

```python
from collections import Counter, defaultdict

words = ["cat", "dog", "cat", "bird", "cat"]
print(Counter(words))   # Counter({'cat': 3, 'dog': 1, 'bird': 1})

groups = defaultdict(list)
groups["fruit"].append("apple")   # no KeyError, list() is auto-created
print(groups)
```

## itertools की मूल बातें

`itertools` जोड़ने और लूप चलाने के लिए मेमोरी-कुशल औज़ार देता है — `chain`, `product`, `combinations` सबसे उपयोगी हैं।

```python
from itertools import chain, combinations

print(list(chain([1, 2], [3, 4])))          # [1, 2, 3, 4]
print(list(combinations("ABC", 2)))         # [('A','B'), ('A','C'), ('B','C')]
```
