Python Cheat Sheet: Lists, Tuples, Dictionaries, and File Operations
Lists
• Lists store multiple items in a single variable, enclosed in [ ].
• Can store any type of data (heterogeneous allowed).
• Indexing starts at 0; negative indices count backward.
• Common functions and operations:
list.append(x) – add item to end
list.pop(i) – remove and return element at index i (default: last)
list.sort() – sort list in place
sorted(list) – return a sorted copy
list.index(x) – return index of first occurrence of x
len(list) – number of elements
list[x:y] – slicing; returns sublist from index x to y-1
• Example:
nums = [2, 4, 6, 8]
nums.append(10)
print(nums[1:4]) # Output: [4,6,8]
Tuples
• Tuples are immutable sequences (cannot be changed after creation).
• Created using parentheses ( ), e.g. my_tuple = (1, 2, 3).
• Single-element tuple requires a comma: (5,).
• Can unpack tuples into variables:
a, b = (1, 2)
• Useful for returning multiple values from a function.
• Tuples are more memory efficient and faster than lists.
Dictionaries
• Store key-value pairs: {key: value}.
• Keys must be immutable (e.g., string, int, tuple).
• Access by key, not index.
• Common methods:
dict.keys() – returns all keys
dict.values() – returns all values
dict.items() – returns (key, value) pairs
dict.get(key, default) – returns value or default if key not found
del dict[key] – removes a key-value pair
• Example:
phonebook = {'Alex': '301-555-1135', 'Brandon': '240-555-2241'}
phonebook['Dana'] = '202-555-5555'
print(phonebook.get('Alex'))
Dictionary Comprehensions
• Similar to list comprehensions:
squares = {x: x**2 for x in range(1, 6)}
• Useful for transforming or filtering key-value pairs.
File Operations
• Opening files:
with open('file.txt', 'r') as f:
content = f.read()
• Modes:
'r' – read
'w' – write (overwrites file)
'a' – append
'r+' – read/write
• Writing:
with open('data.txt', 'w') as f:
f.write('Hello\nWorld')
• Reading:
with open('data.txt', 'r') as f:
for line in f:
print(line.strip())
• Exception handling:
try:
with open('file.txt', 'r') as f:
data = f.read()
except FileNotFoundError:
print("File not found!")