Reference library

Lists & loops

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

5 matches
Lists & loops easy

Convert a List of Integers to a Comma-Separated String in Python

Convert a list of integers into a single comma-separated string using a generator expression and str.join.

join list comma
Python
def ints_to_comma_string(numbers):
    return ",".join(str(num) for num in numbers)

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    result = ints_to_comma_string(numbers)
    print(result)
15 0 Open
Lists & loops easy

How to Convert Data Types in Python Lists

Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.

type-conversion loops lists
Python
def convert_data(data):
    """Convert a mixed list of values to strings, ints, and floats."""
    result = []
    for item in data:
        if isinstance(item, (int, float)):
            result.append(str(item))
        elif isinstance(item, str):
            try:
                if '.' in item:
                    r…
13 0 Open
Lists & loops easy

How to Get the Union of Two Lists Without Duplicates in Python

Merge two lists and remove duplicate values using a set, then convert back to a list.

set union merge
Python
def union_without_duplicates(list1, list2):
    return list(set(list1 + list2))

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [3, 4, 5, 6]
    result = union_without_duplicates(list_a, list_b)
    print(f"Union of {list_a} and {list_b}: {result}")
13 0 Open
Lists & loops easy

How to Process Text with Lists and Loops in Python

Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.

lists loops enumerate
Python
# text_processor.py

def process_text(lines):
    """Count words, show uppercase, and count characters per line."""
    total_words = 0
    print("Line-by-line analysis:")
    for i, line in enumerate(lines, start=1):
        words = line.split()
        total_words += len(words)
        print(f"  Line {i}: {len(words…
17 0 Open
Lists & loops easy

How to Safely Convert a List of Strings to Integers in Python

Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.

list conversion int conversion error handling
Python
def safe_to_int(values):
    """Safely convert a list of strings to integers, skipping invalid entries."""
    result = []
    errors = []
    for value in values:
        try:
            result.append(int(value))
        except (ValueError, TypeError):
            errors.append(value)
    return result, errors


if …
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.