Reference library

Lists & loops

Iterate, transform, and combine sequences with readable loop patterns.

5 matches
Lists & loops easy

Format Lists of Tuples into Numbered Lines in Python

This code loops through a list of (name, grade) tuples and formats each into a numbered line using enumerate and f-strings.

enumerate formatting lists
Python
def format_students(students):
    formatted = []
    for i, student in enumerate(students, start=1):
        name, grade = student
        formatted.append(f"{i}. {name}: {grade}")
    return "\n".join(formatted)


if __name__ == "__main__":
    students = [
        ("Alice", 92),
        ("Bob", 85),
        ("Charl…
15 0 Open
Lists & loops easy

How to Sort a List of Tuples by the Second Element in Python

Sorts a list of tuples by the second element using the sorted() function with a lambda key, preserving the original list.

sorting tuples lambda
Python
def sort_tuples_by_second(tuples_list):
    """Sort a list of tuples by the second element."""
    return sorted(tuples_list, key=lambda x: x[1])


if __name__ == "__main__":
    data = [(1, 5), (3, 2), (2, 8), (4, 1)]
    sorted_data = sort_tuples_by_second(data)
    print("Original list:", data)
    print("Sorted by…
13 0 Open
Lists & loops easy

How to Validate Text Against Forbidden Words in Python

Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.

text validation lists loops
Python
def validate_text(text, forbidden_words):
    """
    Checks that text does not contain any forbidden words.
    Returns (is_valid, offending_words) tuple.
    """
    words = text.lower().split()
    found = [word for word in words if word in forbidden_words]
    return len(found) == 0, found


if __name__ == "__main…
14 0 Open
Lists & loops easy

How to Zip Two Lists into Pairs in Python

Combine two lists element-wise into a list of tuples using Python's built-in zip() function.

zip lists tuples
Python
def zip_lists_into_pairs(list1, list2):
    pairs = list(zip(list1, list2))
    return pairs

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry"]
    quantities = [3, 5, 2]
    result = zip_lists_into_pairs(fruits, quantities)
    print(result)
14 0 Open
Lists & loops easy

How to unzip a list of pairs into two lists in Python

Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.

lists tuples loops
Python
def unzip(pairs):
    """Split a list of (a, b) pairs into two separate lists."""
    if not pairs:
        return [], []
    
    firsts = []
    seconds = []
    for a, b in pairs:
        firsts.append(a)
        seconds.append(b)
    
    return firsts, seconds


if __name__ == "__main__":
    pairs = [(1, 'a'), (…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Lists & loops — Python code examples

What you will find here

This page collects lists & loops snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.