Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514-thinking-16k· AnthropicHugging Face LMArena Human Preference 140K

Python programming language cheat sheet.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    Python programming language cheat sheet.

  2. Claude Assistant

    Here's a comprehensive Python cheat sheet covering essential concepts and syntax:

    Basic Syntax

    # Comments start with #
    """
    Multi-line comments
    use triple quotes
    """
    
    # Variables (no declaration needed)
    x = 5
    name = "Alice"
    pi = 3.14
    is_valid = True
    

    Data Types

    # Numbers
    integer = 10
    float_num = 10.5
    complex_num = 3 + 4j
    
    # Strings
    single = 'Hello'
    double = "World"
    multi = """Multiple
    lines"""
    
    # Type conversion
    int("123")    # 123
    str(456)      # "456"
    float("3.14") # 3.14
    bool(1)       # True
    

    Collections

    # Lists (mutable, ordered)
    my_list = [1, 2, 3, "mixed"]
    my_list.append(4)
    my_list.extend([5, 6])
    my_list.insert(0, 0)
    my_list.pop()
    my_list.remove(2)
    
    # Tuples (immutable, ordered)
    my_tuple = (1, 2, 3)
    x, y, z = my_tuple  # unpacking
    
    # Sets (unordered, unique)
    my_set = {1, 2, 3}
    my_set.add(4)
    my_set.remove(2)
    
    # Dictionaries (key-value pairs)
    my_dict = {"name": "Bob", "age": 30}
    my_dict["city"] = "NYC"
    my_dict.get("name", "default")
    my_dict.keys()
    my_dict.values()
    my_dict.items()
    

    String Operations

    s = "Hello World"
    s.lower()           # "hello world"
    s.upper()           # "HELLO WORLD"
    s.strip()           # remove whitespace
    s.split()           # ["Hello", "World"]
    s.replace("o", "0") # "Hell0 W0rld"
    s.startswith("He")  # True
    s.endswith("ld")    # True
    "_".join(["a", "b"]) # "a_b"
    
    # Formatting
    f"Hello {name}"
    "Hello {}".format(name)
    "Hello %s" % name
    

    Control Flow

    # If/elif/else
    if x > 0:
        print("positive")
    elif x < 0:
        print("negative")
    else:
        print("zero")
    
    # Ternary operator
    result = "yes" if condition else "no"
    
    # For loops
    for i in range(5):
        print(i)
    
    for item in my_list:
        print(item)
    
    for i, value in enumerate(my_list):
        print(f"{i}: {value}")
    
    for key, value in my_dict.items():
        print(f"{key}: {value}")
    
    # While loops
    while x < 10:
        x += 1
        if x == 5:
            continue
        if x == 8:
            break
    

    Functions

    # Basic function
    def greet(name):
        return f"Hello, {name}"
    
    # Default arguments
    def power(base, exp=2):
        return base ** exp
    
    # Variable arguments
    def sum_all(*args):
        return sum(args)
    
    def print_kwargs(**kwargs):
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    
    # Lambda functions
    square = lambda x: x ** 2
    sorted_list = sorted(my_list, key=lambda x: x[1])
    

    List Comprehensions

    # Basic comprehension
    squares = [x**2 for x in range(10)]
    
    # With condition
    evens = [x for x in range(10) if x % 2 == 0]
    
    # Nested comprehension
    matrix = [[i*j for j in range(3)] for i in range(3)]
    
    # Dictionary comprehension
    square_dict = {x: x**2 for x in range(5)}
    
    # Set comprehension
    unique_squares = {x**2 for x in [-2, -1, 0, 1, 2]}
    

    Exception Handling

    try:
        result = 10 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero")
    except Exception as e:
        print(f"Error: {e}")
    else:
        print("No exception occurred")
    finally:
        print("This always runs")
    
    # Raising exceptions
    raise ValueError("Invalid value")
    

    File Operations

    # Reading
    with open("file.txt", "r") as f:
        content = f.read()
        # or line by line
        lines = f.readlines()
    
    # Writing
    with open("file.txt", "w") as f:
        f.write("Hello World")
    
    # Appending
    with open("file.txt", "a") as f:
        f.write("\nNew line")
    

    Classes and Objects

    class Person:
        # Class variable
        species = "Homo sapiens"
        
        def __init__(self, name, age):
            # Instance variables
            self.name = name
            self.age = age
        
        def greet(self):
            return f"Hi, I'm {self.name}"
        
        @classmethod
        def from_birth_year(cls, name, birth_year):
            age = 2025 - birth_year
            return cls(name, age)
        
        @staticmethod
        def is_adult(age):
            return age >= 18
    
    # Inheritance
    class Student(Person):
        def __init__(self, name, age, grade):
            super().__init__(name, age)
            self.grade = grade
    

    Common Built-in Functions

    len([1, 2, 3])          # 3
    max([1, 2, 3])          # 3
    min([1, 2, 3])          # 1
    sum([1, 2, 3])          # 6
    sorted([3, 1, 2])       # [1, 2, 3]
    reversed([1, 2, 3])     # iterator
    abs(-5)                 # 5
    round(3.14159, 2)       # 3.14
    all([True, True])       # True
    any([False, True])      # True
    zip([1, 2], ['a', 'b']) # [(1, 'a'), (2, 'b')]
    

    Modules and Imports

    # Different import styles
    import math
    from math import pi, sqrt
    from datetime import datetime as dt
    import numpy as np
    
    # Common modules
    import os       # Operating system interface
    import sys      # System-specific parameters
    import json     # JSON encoder/decoder
    import random   # Random number generation
    import re       # Regular expressions
    

    Useful One-Liners

    # Swap variables
    a, b = b, a
    
    # Flatten list
    flat = [item for sublist in nested for item in sublist]
    
    # Get unique elements while preserving order
    unique = list(dict.fromkeys(my_list))
    
    # Check if all elements are equal
    all_equal = len(set(my_list)) <= 1
    
    # Transpose matrix
    transposed = list(zip(*matrix))
    
    # Dictionary from two lists
    my_dict = dict(zip(keys, values))
    

    This cheat sheet covers the most frequently used Python features. For more detailed information on any topic, refer to the official Python documentation at python.org.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.