0% found this document useful (0 votes)
0 views6 pages

Python Cheat Sheet

This document provides a comprehensive cheat sheet for common Python data structures, including Lists, Tuples, Sets, Dictionaries, Strings, Arrays, Deques, and Linked Lists, along with their key operations and examples. Each data structure is described in terms of its mutability, order, and typical operations, with code snippets for clarity. Additionally, it includes a summary table for quick reference on the characteristics of each data structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views6 pages

Python Cheat Sheet

This document provides a comprehensive cheat sheet for common Python data structures, including Lists, Tuples, Sets, Dictionaries, Strings, Arrays, Deques, and Linked Lists, along with their key operations and examples. Each data structure is described in terms of its mutability, order, and typical operations, with code snippets for clarity. Additionally, it includes a summary table for quick reference on the characteristics of each data structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Python Data Structures Operations Cheat Sheet

(with Examples)
Below are common Python data structures and typical operations—each illustrated with code
examples. The included linked list is implemented using a custom class, as Python's standard
library does not provide a built-in linked list.

1. List
Flexible, mutable, ordered sequence.

# Creation
lst = [1, 2, 3]

# Access by index
print(lst[0]) # 1

# Slicing
print(lst[1:3]) # [2, 3]

# Append
lst.append(4) # [1, 2, 3, 4]

# Insert
lst.insert(1, 'a') # [1, 'a', 2, 3, 4]

# Remove by value
lst.remove('a') # [1, 2, 3, 4]

# Remove by index
lst.pop(1) # returns 2; list is now [1, 3, 4]

# Check existence
print(4 in lst) # True

# Sort
lst.sort() # [1, 3, 4]

# Reverse
lst.reverse() # [4, 3, 1]
2. Tuple
Immutable, ordered.

# Creation
tpl = (1, 2, 3)

# Access by index
print(tpl[2]) # 3

# Slicing
print(tpl[:2]) # (1, 2)

# Count value
print(tpl.count(1)) # 1

# Find index
print(tpl.index(2)) # 1

# Concatenate
tpl2 = tpl + (4, 5) # (1, 2, 3, 4, 5)

# Membership test
print(2 in tpl) # True

3. Set
Unordered, mutable, unique elements.

# Creation
s = {1, 2, 3}

# Add element
s.add(4) # {1, 2, 3, 4}

# Remove element
s.remove(2) # {1, 3, 4}

# Discard element (no error if not present)


s.discard(2)

# Union
print(s.union({5, 6})) # {1, 3, 4, 5, 6}

# Intersection
print(s.intersection({3, 7})) # {3}

# Subset check
print({1, 3}.issubset(s)) # True

# Membership test
print(4 in s) # True
4. Dictionary
Key-value pairs, unordered, mutable.

# Creation
d = {'a': 1, 'b': 2}

# Access by key
print(d['a']) # 1

# Set new value


d['c'] = 3

# Remove by key
d.pop('b') # {'a': 1, 'c': 3}

# Get value with default


print(d.get('b', 'not found')) # not found

# Keys, values, items


print(list(d.keys())) # ['a', 'c']
print(list(d.values())) # [1, 3]
print(list(d.items())) # [('a', 1), ('c', 3)]

# Update
d.update({'d': 4})

5. String
Immutable, ordered Unicode characters.

# Creation
s = "hello"

# Indexing and slicing


print(s[1]) # 'e'
print(s[1:4]) # 'ell'

# Length
print(len(s)) # 5

# Concatenate, repeat
print(s + " world") # 'hello world'
print(s * 2) # 'hellohello'

# Find substring
print(s.find('ll')) # 2

# Replace substring
print(s.replace('l', 'x')) # 'hexxo'

# Split and join


words = 'a,b,c'.split(',') # ['a', 'b', 'c']
print(','.join(words)) # 'a,b,c'

6. Array (array module)


Efficient array with fixed data type.

from array import array

# Creation
arr = array('i', [1, 2, 3])

# Append
arr.append(4) # array('i', [1, 2, 3, 4])

# Insert
arr.insert(0, 9) # array('i', [9, 1, 2, 3, 4])

# Remove
arr.remove(2) # array('i', [9, 1, 3, 4])

# Pop
val = arr.pop() # Removes 4

# Slicing
print(arr[1:3]) # array('i', [1, 3])

7. Deque (collections module)


Double-ended queue.

from collections import deque

# Creation
dq = deque([1, 2, 3])

# Append right/left
dq.append(4) # deque([1, 2, 3, 4])
dq.appendleft(0) # deque([0, 1, 2, 3, 4])

# Pop right/left
dq.pop() # removes 4
dq.popleft() # removes 0

# Extend right/left
dq.extend([5, 6]) # deque([1, 2, 3, 5, 6])
dq.extendleft([-1, -2]) # deque([-2, -1, 1, 2, 3, 5, 6])

# Rotate
dq.rotate(2) # rotates right by 2
8. Linked List (Custom Class Example)
Python does not have a built-in linked list, but it can be implemented with classes:

class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def append(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
return
curr = self.head
while curr.next:
curr = curr.next
curr.next = new_node

def find(self, key):


curr = self.head
while curr:
if curr.data == key:
return True
curr = curr.next
return False

def delete(self, key):


curr = self.head
prev = None
while curr:
if curr.data == key:
if prev:
prev.next = curr.next
else:
self.head = curr.next
return True
prev, curr = curr, curr.next
return False

def print_list(self):
curr = self.head
while curr:
print(curr.data, end=" ")
curr = curr.next
print()

# Usage
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.print_list() # 1 2 3
print(ll.find(2)) # True
ll.delete(2)
ll.print_list() # 1 3

9. Other Useful Structures


NamedTuple:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y) # 1 2

Heap (Priority Queue):


import heapq
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
print(heapq.heappop(heap)) # 1

Data Structures Summary Table


Type Mutable Ordered Key Operations Example

List Yes Yes append, pop, sort

Tuple No Yes count, index

Set Yes No add, remove, union

Dict Yes No get, pop, update

String No Yes find, split, replace

Array Yes Yes append, insert, pop

Deque Yes Yes appendleft, popleft

LinkedList Yes* Yes append, delete, traverse

*Custom implementations of linked lists are mutable.

You might also like