Python Data Structures Cheat Sheet: The Essential Guide

Python Data Structures Cheat Sheet

Do you want to pick out elements from a list of objects but forgot how to do list comprehension? Or maybe you have a JavaScript Object Notation (JSON) file and need to find a suitable data structure (such as Python's dictionary data type) to process the data in it. Browsing app development forums to find a helpful piece of Python code can be frustrating.

The good news is we’ve prepared this cheat sheet for people like you. It doubles as a refresher on data structures and algorithms as applied to Python. Keep a copy of this Python data structures cheat sheet on your desk to look up commands or code snippets the next time you need to recall them.

This Python data structures cheat sheet covers the theoretical essentials. Download the PDF version here.

Python Data Structures Cheat Sheet Search

Search our Python data structures cheat sheet to find the right cheat for the term you're looking for. Simply enter the term in the search bar and you'll receive the matching cheats available.

Types of Data Structures in Python

Here’s a diagram to illustrate the hierarchy of Python data structures:

Python Data Structures - diagram by author redesigned by StationX team

Python Primitive Data Structures

These store simple data values.

DescriptionExamples
StringCollection of characters surrounded by single or double quotation marks'Alice', "Bob"
BooleanLogical valuesTrue, False
IntegerWhole number of unlimited length0, -273
FloatFloating-point decimal1.618, 3.1415926

Python Built-In Non-Primitive Data Structures

These data structures, which store values and collections of values, are inherent to Python.

DescriptionOrderedAllow duplicatesMutableSyntaxExamples
List√√√[ ]β€’ [1, 2.3, True]
β€’ ['John', 'Doe']
Tupleβˆšβˆšβœ•( )β€’ ('age', 22)
β€’ (7.89, False)
Set

0 is the same as False, as are 1 and True.
βœ•βœ•βœ•{ }β€’ {6, 4.5}
β€’ {'nice', True}
Dictionary

Map, storing key-value pairs.
√ > 3.7
βœ• ≀ 3.6
βœ•βˆš{key: value}β€’ {"FB": "Facebook",
"WA": "WhatsApp",
"IG": "Instagram"}

β€’ {'name': 'Bob', 'id': 255}

List and Tuple Operations

Note that Python lists and tuples are zero-indexed, meaning the first element has an index of 0. See the command chart below for an example.

Accessing Items in Lists

The table below is based on this list:

fruit_list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"].

CommandDescription
fruit_list[0]Get the first item on the list ("apple")
fruit_list[1]Get the second item on the list ("banana")
fruit_list[-1]Get the last item ("mango")
fruit_list[Β­2:5]Get the items from start to end indexes
fruit_list[:4]Get the items from the beginning but exclude "kiwi" and beyond
fruit_list[2:]Get the items from "Β­cheΒ­rryΒ­" to the end
fruit_list[Β­-4:-1]Get the items from "Β­oraΒ­ngeΒ­" (-4) onwards but exclude "Β­manΒ­go" (-1)
if "Β­appΒ­le" in fruit_list:
   print(Β­"Yes, we have 'apple'")
Check if "Β­appΒ­le" is in the list

List (and Tuple) Methods

Commands with an asterisk (*) apply to tuples.

CommandDescriptionUsage
append()Add an element at the end of the listlist1.aΒ­ppend(element)
clear()Remove all the elements from the listlist1.cΒ­lear()
copy()Return a copy of the listlist1.cΒ­opy()
count()Return the number of elements with the specified value*list1.cΒ­ounΒ­t(eΒ­lement)
extend()Add the elements of a list (or any iterable), to the end of the current listlist1.eΒ­xtΒ­endΒ­(list2)
index()Return the index of the first element with the specified value*list1.iΒ­ndeΒ­x(eΒ­lemΒ­entΒ­[,sΒ­tarΒ­t[,Β­end]])
insert()Add an element at the specified position (position is an integer)list1.iΒ­nseΒ­rt(Β­poΒ­sition, element)
pop()Remove the element at the specified positionlist1.pΒ­op(Β­[inΒ­dex])
remove()Remove the first item with the specified valuelist1.rΒ­emoΒ­ve(Β­eleΒ­ment)
reverse()Reverse the order of the listlist1.reΒ­verse()
sort()
sort(reverse = True)
Sort the list in ascending / descending orderlist1.sort()
list2.sort(reverse = True)
del()Delete from the list the item specified with its indexdel list1[Β­index]
list1 + list2Join two listslist1 = ["x", "y"]
list2 = [8, 9]
list3 = list1 + list2

# Returns: ["x","y",8,9]

List Comprehension

List compreΒ­hension simplifies the creation of a new list based on the values of an existing list.

CommandDescription
[n for n in range(10) if n < 5]Accept only numbers less than 5
[x for x in fruits if "Β­a" in x]Accept items containing "Β­a".
[x for x in fruits if x != "Β­appΒ­le"]Accept all items except "Β­appΒ­le"
[x.upper() for x in fruits]Make uppercase the values in the new list
[x + '?' for x in fruits]Add a question mark at the end of each item
['hello' for x in fruits]Set all values in the new list to 'hello'
[x if x != "Β­banΒ­anaΒ­" else "Β­oraΒ­ngeΒ­" for x in fruits]Replace "Β­banΒ­anaΒ­" with "Β­oraΒ­ngeΒ­" in the new list

Accessing Items in Tuples

Below, the tuple in question is fruits = ("apple", "banana", "cherry").

CommandDescription
"Β­appΒ­le" in fruitsCheck if "Β­appΒ­le" is present in the tuple. This command returns the value True.
(x, y, z) = fruits
# x == "apple"

# y == "banana"
# z == "cherry"
(a, *_) = fruits
# a == "apple"

# _ == ["banana", "cherry"]
Assign variables to take up each item in the tuple, also known as unpacking a tuple.

Either the number of variables must match the number of values in the tuple, or use an asterisk as shown to put away the unwanted values.

Tuple Manipulation

Adding items

You can add items to a tuple as follows:

Initialoriginal = ("apΒ­pleΒ­", "Β­banΒ­anaΒ­", "Β­cheΒ­rryΒ­")
Codenew_item = ("orΒ­angΒ­e",)
original += new_item
Result("apΒ­pleΒ­", "Β­banΒ­anaΒ­", "Β­cheΒ­rryΒ­", "orange")

Tip: When creating a single-item tuple, remember to include a comma.

Removing items and changing values

Since tuples are immutable, you can’t remove or modify their contents directly. The key is converting it into a list and back.

ExampleAdditionRemovalChange
Initialoriginal = ("apΒ­pleΒ­", "Β­banΒ­anaΒ­", "Β­cheΒ­rryΒ­")original = ("apΒ­pleΒ­", "Β­banΒ­anaΒ­", "Β­cheΒ­rryΒ­")original = ("apΒ­pleΒ­", "Β­banΒ­anaΒ­", "Β­cheΒ­rryΒ­")
β†’ ListtempList = list(original)tempList = list(original)tempList = list(original)
CodetempList.appeΒ­nd(Β­"Β­oraΒ­ngeΒ­")tempList.remoΒ­ve(Β­"Β­appΒ­le")tempList[1] = "Β­kiwΒ­i"
β†’ TuplenewList = tuple(tempList)newList = tuple(tempList)newList = tuple(tempList)
Result of newList("apΒ­pleΒ­", "Β­banΒ­anaΒ­", "Β­cheΒ­rryΒ­", "orange")("Β­banΒ­anaΒ­", "Β­cheΒ­rryΒ­")("kiwi", "Β­banΒ­anaΒ­", "Β­cheΒ­rryΒ­")

Dictionary Operations

Adding Items

There are three methods:

ExampleAddition #1 (direct)Addition #2 (update())Addition #3 (**)
Initialmeta = { "FB": "Facebook", "WA": "WhatsApp", "IG": "Instagram" }

new_co = { "GIF": "Giphy" }
meta = { "FB": "Facebook", "WA": "WhatsApp", "IG": "Instagram" }

new_co = { "GIF": "Giphy" }
meta = { "FB": "Facebook", "WA": "WhatsApp", "IG": "Instagram" }

new_co = { "GIF": "Giphy" }
Codemeta[Β­"GIF"] = "Giphy"meta.update(new_co)meta = {**meta, **new_co}
Result of meta{ "FB": "Facebook", "WA": "WhatsApp", "IG": "Instagram", "GIF": "Giphy" }{ "FB": "Facebook", "WA": "WhatsApp", "IG": "Instagram", "GIF": "Giphy" }{ "FB": "Facebook", "WA": "WhatsApp", "IG": "Instagram", "GIF": "Giphy" }

Warning: duplicate keys will cause the latest values to overwrite earlier values.

General Operations

CommandDescriptionExample
del dict1[Β­"key1"]Remove the item with the specified key namedel meta[Β­"WA"]
# "WhatsApp"
del diΒ­ct1Delete the dictionarydel meta
dict1[key1]Access the value of a dictionary dict1 element using its key key1meta["FB"]# "Facebook"
Dictionary methodDescriptionUsage
clear()Remove all the elements from the dictionarydict1.cΒ­lear()
copy()Return a copy of the dictionarydict1.cΒ­opy()
fromkeys()Return a dictionary with the specified keys and valuedict1.fΒ­romΒ­keyΒ­s(keys, value)
get()Return the value of the specified keydictioΒ­narΒ­y.gΒ­et(Β­keyΒ­_name, value)
items()Return a list containing a tuple for each key-value pairdict1.iΒ­tems()
keys()Return a list containing the dictioΒ­nary’s keysdict1.kΒ­eys()
pop()Remove the element with the specified keydict1.pΒ­op(keΒ­y_name)
popitem()Remove the last inserted key-value pairdict1.pΒ­opiΒ­tem()
setdefΒ­ault()Return the value of the specified key. If the key does not exist, add as new key-value pairdict1.sΒ­etdΒ­efaΒ­ultΒ­(keΒ­y_name, value)
update()Update the dictionary with the specified key-value pairsdict1.uΒ­pdaΒ­te(Β­iteΒ­rable)
values()Return a list of all the values in the dictionarydict1.vΒ­alues()

Set Operations

Accessing

Although you can’t directly access items in a set, you can loop through the items:

ExampleAccessing items in a set (using list comprehension)
Codeset1 = {32, 1, 2, 27, 83, 26, 59, 60}
set1_odd = [i for i in set1 if i % 2 == 1]
Resultset1_odd = [1, 27, 83, 59]

Adding and Removing Items

CommandDescriptionUsage
add()Add a single element to the setfruits.aΒ­dd(Β­"Β­oraΒ­ngeΒ­")
update()Add elements from another set into this setfruits.aΒ­dd(Β­{"piΒ­neaΒ­pplΒ­e", "Β­manΒ­go", "durian"})
discard()
remove()
Remove the specified elementfruits.dΒ­iscΒ­ardΒ­("baΒ­nanΒ­a")
fruits.rΒ­emoΒ­ve(Β­"Β­banΒ­anaΒ­")
pop()Remove the last element in the set. The return value of bye is the removed element.bye = fruits.pop()
clear()Empty the setfruits.clear()
copy()Return a copy of the setfruits.copy()
delDelete the setdel fruits

Mathematical Operations

Command / Binary operator(s)Description
differΒ­ence()
-
Get the difference of several sets
differΒ­encΒ­e_uΒ­pdate()Remove the elements in this set that are also included in another, specified set
intersΒ­ectΒ­ion()
&
Get intersection of sets
intersΒ­ectΒ­ionΒ­_upΒ­date()Remove the elements in this set that are not present in other, specified set(s)
isdisjΒ­oint()Return whether two sets have an intersΒ­ection
issubset()
<, <=
Check if a set is a (strict <) subset
issupeΒ­rset()
>, >=
Check if a set is a (strict >) superset
symmetΒ­ricΒ­_diΒ­ffeΒ­rence()
^
Get symmetric differΒ­ence of two sets
symmetric_difference_update()Insert the symmetric differΒ­ences from this set and another
union()
|
Get the union of sets

Algorithms and the Complexities

This section is about the complexity classes of various Python data structures.

List

Tuples have the same operations (non-mutable) and complexities.

Command (L: list)Complexity class
L.append(item)O(1)
L.clear()O(1)
item in/not in LO(N)
L.copy()O(N)
del L[i]O(N)
L.extend(…)O(N)
L1==L2, L1!=L2O(N)
L[i]O(1)
for item in L:O(N)
len(L)O(1)
k*LO(k*N)
min(L), max(L)O(N)
L.pop(-1)O(1)
L.pop(item)O(N)
L.remove(…)O(N)
L.reverse()O(N)
L[x:y]O(y-x)
L.sort()O(N*log(N))
L[i]=itemO(1)

Dictionary

Command (d: dictionary)Complexity class / range (β€”)
d.clear()O(1)
dict(…)O(len(d))
del d[k]O(1) β€” O(N)
d.get()O(1) β€” O(N)
for item in d:O(N)
len(d)O(1)
d.pop(item)O(1) β€” O(N)
d.popitem()O(1)
d.values()O(1)
d.keys()O(1)
d.fromkeys(seq)O(len(seq))

Set

OperationCommand (s: set)Complexity class / range (β€”)
Adds.add(item)O(1) β€” O(N)
Clears.clear()O(1)
Copys.copy()O(N)
Containmentitem in/not in sO(1) β€” O(N)
Creationset(…)O(len(s))
Discards.discard(item)O(1) β€” O(N)
Differences1-s2O(len(s1))
Difference Updates1.difference_update(s2)O(len(s2)) β€” ∞
Equalitys1==s2, s1!=s2O(min(len(s1), len(s2)))
Intersections1&s2O(min(len(s1), len(s2)))
Iterationfor item in s:O(N)
Is Subsets1<=s2O(len(s1))
Is Supersets1>=s2O(len(s2)) β€” O(len(s1))
Pops.pop()O(1) β€” O(N)
Unions1|s2O(len(s1)+len(s2)) β€” ∞
Symmetric Differences1^s2O(len(s1)) β€” O(len(s1)*len(s2))

Symbol Table

Python keeps track of variables using symbol tables, which you can explore using the following basic commands:

CommandDescription
__doc__Program documentation as comments (#, """, ''') at the beginning of the code
__name__How you run the Python program.Direct execution: __name__ == "__main__"
dir()Effective namespace
global()Dictionary of variable names of global scope to variable values
locals()Dictionary of variable names of local scope to variable values
eval()Return the value of the specified variable
Example usage:for x in dir(): print(x, eval(x))

Python Libraries

The following commands are for setting up Python programs or libraries for use inside your program:

CommandDescription
import module1Import program / library  module1 as Python module
from module1 import obj1, obj2Import the objects obj1, obj2 from module1
from module1 import *Import all objects in module1
module1.__dict__Return the dictionary containing module1’s symbol table, like dir() of the main program

Examples of Python libraries containing other non-primitive data structures:

  • array: Efficient arrays of numeric values
  • collections: Abstract data structures
  • dataclasses: For creating user-defined data structures
  • datetime: Basic date and time types
  • queue: Synchronized queue class

Experience Software Development

Much of the above is crucial in developing apps for commercial settings, including freelancing. We hope this Python data structures cheat sheet is helpful. To download a PDF version, click here.

At StationX, we have self-paced Python tutorials and labs focusing on cybersecurity. Check out our StationX Membership to learn more.

Frequently Asked Questions

Level Up in Cyber Security: Join Our Membership Today!

vip cta image
vip cta details
  • Cassandra Lee

    Cassandra is a writer, artist, musician, and technologist who makes connections across disciplines: cyber security, writing/journalism, art/design, music, mathematics, technology, education, psychology, and more. She's been a vocal advocate for girls and women in STEM since the 2010s, having written for Huffington Post, International Mathematical Olympiad 2016, and Ada Lovelace Day, and she's honored to join StationX. You can find Cassandra on LinkedIn and Linktree.

>

StationX Accelerator Pro

Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Accelerator Pro Program. Stay tuned for more!

StationX Accelerator Premium

Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Accelerator Premium Program. Stay tuned for more!

StationX Master's Program

Enter your name and email below, and we’ll swiftly get you all the exciting details about our exclusive StationX Master’s Program. Stay tuned for more!