Reference library

Lists & loops

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

9 matches
Lists & loops easy

Extract Data by Type from a List in Python: Numbers and Strings

Loop through a mixed list to filter out numeric and string values into separate lists.

lists filtering type-checking
Python
def extract_numbers(items):
    """Extract all numeric values from a mixed list."""
    numbers = []
    for item in items:
        if isinstance(item, (int, float)) and not isinstance(item, bool):
            numbers.append(item)
    return numbers


def extract_strings(items):
    """Extract all string values from a…
14 0 Open
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 Build a Text Processor with Lists and Loops in Python

A beginner-friendly Python script that analyzes text by counting sentences, words, and word lengths using lists and for loops, then prints the results.

text-processing loops lists
Python
def process_text(text):
    """Simple text processor for beginners using lists and loops."""
    sentences = text.replace('!', '.').replace('?', '.').split('.')
    words = text.split()
    
    word_counts = []
    for sentence in sentences:
        sentence_word_count = len(sentence.split())
        word_counts.appe…
12 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 Filter Empty Strings in Python

Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.

filtering strings list-comprehension
Python
def filter_empty_strings(strings):
    """
    Filter out empty strings (including whitespace-only strings)
    from a list of strings.
    """
    return [s for s in strings if s.strip()]


if __name__ == "__main__":
    sample_list = ["hello", "", "world", "   ", "python", " ", "!"]
    filtered = filter_empty_strin…
12 0 Open
Lists & loops easy

How to Parse Delimited Data into a Python List

Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.

strings lists loops
Python
def parse_data(raw_data):
    """Parse a pipe-delimited string into a list of cleaned items."""
    items = raw_data.split("|")
    parsed = []
    for item in items:
        cleaned = item.strip()
        if cleaned:
            parsed.append(cleaned)
    return parsed


if __name__ == "__main__":
    data = "  apple…
15 0 Open
Lists & loops easy

How to Process Text into Words in Python

Splits a string into words, strips punctuation, and returns a list of uppercase words using a loop.

text-processing loops strings
Python
def convert_text_processor(text):
    words = text.split()
    processed = []
    
    for word in words:
        clean = word.strip('.,!?;:')
        if len(clean) > 0:
            processed.append(clean.upper())
    
    return processed

if __name__ == "__main__":
    sample_text = "Hello, world! This is a Python e…
12 0 Open
Lists & loops easy

How to Process Text with Lists and Loops in Python

A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.

lists loops strings
Python
text = "Python makes text processing easy and fun"

words = text.lower().split()

print("Words in the sentence:")
for index, word in enumerate(words, start=1):
    print(f"{index}. {word}")

filtered_words = [word for word in words if len(word) > 3]

print(f"\nWords longer than 3 characters: {filtered_words}")

letter…
14 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.