<jupyter_start><jupyter_text>6.1 Writing Pythonic Loops  Non pythonic way<jupyter_code>my_items = ['a', 'b', 'c']
i = 0

while i < len(my_items):
    print(my_items[i])
    i += 1<jupyter_output>a
b
c<jupyter_text>pythonic-ish way<jupyter_code>for i in range(len(my_items)):
    print(my_items[i])<jupyter_output>a
b
c<jupyter_text>pythonic way<jupyter_code>for item in my_items:
    print(item)<jupyter_output>a
b
c<jupyter_text>It’s possible to write loops that keep a running index while avoiding the range(len(...)) pattern I cautioned against. The enumerate() built-in helps you make those kinds of loops nice and Pythonic:<jupyter_code>for i, item in enumerate(my_items):
    print(f'{i}: {item}')


# This is very powerful. For example, you can use the same technique
# to iterate over the keys and values of a dictionary at the same time:
emails = {
    'Bob': '<EMAIL>',
    'Alice': '<EMAIL>',
}

for name, email in emails.items():
    print(f'{name} -> {email}')<jupyter_output>0: a
1: b
2: c
Bob -> <EMAIL>
Alice -> <EMAIL>
{'fraction_non_alphanumeric': 0.13333333333333333, 'fraction_numerical': 0.00676328502415459, 'mean_word_length': 4.820224719101123, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '477728', 'license': 'MIT', 'n_tokens_mistral': 405, 'n_tokens_neox': 402, 'n_words': 117, 'path': '2022/Python-Tricks-Book/Chapter6-looping-iteration/pythonic-loops.ipynb', 'repo_name': 'Muramatsu2602/python-study', 'size': '1071'}