Python Data Types Cheat Sheet β€” int, str, list, dict, set, tuple | Dataplexa

Python Data Types

int  Β·  float  Β·  str  Β·  list  Β·  dict  Β·  tuple  Β·  set  Β·  methods  Β·  slicing  Β·  mutability

Sheet 2 of 10 Python 3.x Beginner Printable

All Built-in Types at a Glance

quick reference
TypeCategoryMutable?Ordered?Duplicates?Literal syntaxUse when…
int Numeric No β€” β€” 42 -7 0b1010 Whole numbers, counting, indexing
floatNumeric No β€” β€” 3.14 1e3 Decimals, measurements, math
bool Numeric No β€” β€” True False Flags, conditions
str Sequence No Yes Yes"hi" 'hello' """...""" Text, names, messages
list Sequence Yes YesYes[1, 2, 3] Ordered, changeable collection
tupleSequence No YesYes(1, 2, 3) Fixed data, dict keys, returns
dict Mapping Yes Yes*Keys: No{"k": "v"} Key→value lookup, config
set Set Yes No No {1, 2, 3} Unique items, membership tests
frozensetSet No No No frozenset({1,2}) Immutable set, hashable
* dict insertion order is preserved since Python 3.7. Values can be duplicates; keys cannot.

str β€” Strings

immutable sequence
Creating Strings
s1 = "Hello"
s2 = 'World'
s3 = """Multi
line"""
s4 = r"C:\new\path"   # raw str
s5 = 3 * "ha"          # "hahaha"
s6 = "Hi" + " there"   # concat
Slicing β€” s[start : stop : step]
s = "Python"
s[0]       # "P"  β€” first char
s[-1]      # "n"  β€” last char
s[0:3]     # "Pyt"
s[2:]      # "thon"
s[:4]      # "Pyth"
s[::2]     # "Pto" β€” every 2nd
s[::-1]    # "nohtyP" β€” reversed
String Methods β€” Transform
s = "  Hello World  "
s.upper()          # "  HELLO WORLD  "
s.lower()          # "  hello world  "
s.title()          # "  Hello World  "
s.strip()          # "Hello World"
s.lstrip()         # "Hello World  "
s.rstrip()         # "  Hello World"
s.replace("World","Python")
s.center(20, "*")   # pad with *
s.zfill(10)         # pad with zeros
String Methods β€” Search & Split
s = "hello world"
s.find("world")     # 6  (index)
s.find("xyz")       # -1 (not found)
s.index("world")    # 6  (raises if missing)
s.count("l")        # 3
s.startswith("he")  # True
s.endswith("ld")    # True
s.split()          # ["hello","world"]
s.split(" ",1)      # split max 1 time
" ".join(["a","b"]) # "a b"
s.isdigit()        # False
s.isalpha()        # False (has space)
Strings are immutable β€” every method returns a new string, the original is never changed. Use f"Hello {name}" for formatting (Python 3.6+).

list

mutable Β· ordered Β· duplicates ok
Create & Access
fruits = ["apple", "banana", "cherry"]
mixed  = [1, "hi", True, None]  # any types
nested = [[1,2], [3,4]]

fruits[0]    # "apple"  (first)
fruits[-1]   # "cherry" (last)
fruits[1:3]  # ["banana","cherry"]
len(fruits)  # 3
Modify Methods
fruits.append("mango")       # add to end
fruits.insert(1, "orange")    # insert at index
fruits.extend(["kiwi","fig"])  # add multiple
fruits.remove("banana")       # remove by value
fruits.pop()                   # remove last
fruits.pop(0)                 # remove by index
fruits.sort()                  # sort in-place
fruits.sort(reverse=True)     # descending
fruits.reverse()               # flip order
fruits.clear()                 # empty the list
Query Methods
fruits.index("apple")  # position of value
fruits.count("apple")  # how many times
copy = fruits.copy()  # shallow copy
sorted(fruits)         # new sorted list
"apple" in fruits     # True / False
copy vs reference: b = a makes both point to the same list. Use b = a.copy() or b = a[:] for an independent copy.

tuple

immutable Β· ordered Β· duplicates ok
Create & Access
coords  = (10.0, 20.5)
rgb     = (255, 128, 0)
single  = (42,)         # trailing comma!
packed  = 1, 2, 3        # parens optional

coords[0]       # 10.0
coords[-1]      # 20.5
len(coords)     # 2

# Tuple unpacking
x, y = coords
a, *rest = (1, 2, 3, 4)  # a=1, rest=[2,3,4]
Methods & Operations
t = (1, 2, 2, 3)
t.count(2)   # 2  β€” occurrences
t.index(3)   # 3  β€” first position
2 in t       # True

# Convert to/from list
lst = list(t)
t2  = tuple(lst)
Use tuples for: coordinates, RGB values, function return of multiple values, dict keys (lists can't be dict keys β€” tuples can).

dict β€” Dictionary

mutable Β· ordered (3.7+) Β· keys unique
Create & Access
user = {
    "name":  "Alice",
    "age":   25,
    "active": True
}

# Access by key
user["name"]           # "Alice"
user.get("age")        # 25
user.get("score", 0)  # 0 (default)

# Add / update
user["email"] = "a@b.com"
user["age"]   = 26         # update
Useful Methods
user.keys()           # dict_keys([...])
user.values()         # dict_values([...])
user.items()          # dict_items([(k,v)...])
user.pop("active")   # remove key, return val
user.update({"age":27})   # merge
user.setdefault("role","user")
user.copy()           # shallow copy
user.clear()          # empty dict
"name" in user        # True (checks keys)
Looping & Dict Comprehension
# Loop keys
for key in user:
    print(key)

# Loop key-value pairs
for k, v in user.items():
    print(f"{k}: {v}")

# Dict comprehension
squares = {n: n**2 for n in range(5)}
# {0:0, 1:1, 2:4, 3:9, 4:16}

# Merge dicts (Python 3.9+)
merged = dict1 | dict2
KeyError: Accessing a missing key with d["key"] raises KeyError. Use d.get("key") to return None safely, or d.get("key", default) for a fallback value.

set

mutable Β· unordered Β· unique only
Create & Basic Ops
s = {1, 2, 3, 2, 1}   # β†’ {1, 2, 3}
s = set([1,2,2,3])     # from list
empty = set()           # NOT {} (that's dict!)

s.add(4)
s.remove(2)       # KeyError if missing
s.discard(99)     # safe remove β€” no error
3 in s             # True β€” O(1) lookup
Set Operations
a = {1,2,3};  b = {2,3,4}

a | b    # {1,2,3,4}  union
a & b    # {2,3}      intersection
a - b    # {1}        difference
a ^ b    # {1,4}      symmetric diff

# Method equivalents
a.union(b)
a.intersection(b)
a.difference(b)
a.issubset(b)     # is a βŠ† b?
a.issuperset(b)   # is a βŠ‡ b?
Best use: Remove duplicates from a list with list(set(my_list)). Fast O(1) membership tests. Cannot index β€” no s[0].

Converting Between Types

casting
FunctionFromToExample β†’ Result
int() str, float, boolint int("42") β†’ 42
float() str, int, bool floatfloat("3.14") β†’ 3.14
str() any str str(100) β†’ "100"
bool() any bool bool(0) β†’ False
list() str, tuple, setlist list("abc") β†’ ["a","b","c"]
tuple() list, str, set tupletuple([1,2]) β†’ (1,2)
set() list, tuple, strset set([1,1,2]) β†’ {1,2}
dict() list of pairs dict dict([("a",1)]) β†’ {"a":1}
Common Patterns
# Remove duplicates
list(set([1,2,2,3]))       # [1, 2, 3]

# String to list of chars
list("hello")              # ["h","e","l","l","o"]

# Two lists β†’ dict
dict(zip(["a","b"], [1,2]))  # {"a":1,"b":2}

Slicing β€” Universal Reference

str Β· list Β· tuple
Syntax & Index Rules
# seq[start : stop : step]
# stop is EXCLUDED
# Negative index counts from end

s = [0,1,2,3,4,5]
#   0  1  2  3  4  5   ← positive
#  -6 -5 -4 -3 -2 -1   ← negative

s[0]        # 0   β€” first
s[-1]       # 5   β€” last
s[2:5]      # [2,3,4]
s[:3]       # [0,1,2]
s[3:]       # [3,4,5]
Step & Reverse
s = [0,1,2,3,4,5]
s[::2]      # [0,2,4]  every 2nd
s[1::2]     # [1,3,5]  odd indices
s[::-1]     # [5,4,3,2,1,0] reversed
s[4:1:-1]   # [4,3,2]

# Works on strings too
"Python"[::-1]   # "nohtyP"
"Python"[:3]     # "Pyt"
Modifying Lists via Slice
s = [0,1,2,3,4]

# Replace slice
s[1:3] = [10,20]
# [0,10,20,3,4]

# Delete slice
del s[2:4]
# [0,10,4]

# Full copy via slice
copy = s[:]     # independent copy

Choosing the Right Type

decision guide
ScenarioBest TypeReason
Store a person's name str Text data
Shopping cart items that can change list Ordered, mutable, allows duplicates
GPS coordinates (lat, lng) tupleFixed pair β€” immutable makes sense
User profile (name, age, email) dict Named fields via key-value
Tags on an article (no repeats) set Unique items, fast lookup
Days of the week (fixed, reusable) tupleImmutable constant data
Check if username is already taken set O(1) membership test
Count word frequency in a text dict Map word β†’ count
Return x, y, z from a function tupleMultiple return values, unpacking
Config settings (key: value pairs) dict Named access, easy to update

Data Types Mastery Checklist

sheet 2 complete
str & SlicingKey point
Create strings 3 ways " " ' ' """ """
Slice any sequence s[start:stop:step]
Reverse a string s[::-1]
Split and join strings .split() / .join()
Check content type .isdigit() .isalpha()
list Β· tuple Β· setKey point
Append & remove from list .append() .remove()
Unpack a tuple x, y = (1, 2)
Create an empty set set() not {}
Set union / intersection a | b / a & b
Copy a list safely a.copy() or a[:]
dictKey point
Access with fallback .get("k", default)
Loop key-value pairs .items()
Merge two dicts d1 | d2 / .update()
Check key exists "key" in d
Build with comprehension {k: v for …}
Next up β†’ Sheet 3: Python Functions  Β·  def Β· return Β· args Β· *args Β· **kwargs Β· lambda Β· scope Β· default params Β· docstrings