The Python Data Structures Cheat Sheet [PDF Included]

Download the python cheatsheet: [PDF]

A data structure is a ubiquitous concept among programming languages and allows for the organization and storage of data in computer programs. This concise guide covers the four builtin data structures in python which are lists, tuples, sets, and dictionaries. There’s more specialized data structures which build upon these four data structures which can be found in the collections module.

Lists

  • Lists are an ordered sequencable mutable data types in python.
  • Heterogeneous elements are permitted, but lists are stereotypically homogeneous.
  • Lists can be indexed, sliced, iterated, and tested for membership inclusion.
  • Lists can be nested, or a list within a list is permitted.

Syntax for creating a list:

>>>  nums = [2, 4, 6, 8, 10]

List indexing:

>>> nums[0]
2

Negative indexes are allowed:

>>> nums[-1]
10

List slicing

>>> nums[3:]
[8, 10]

List comprehension

List comprehensions allows you to create lists with more concise notation.

>>> [x for x in range(10) if  x % 2 == 0 ]
[0, 2, 4, 6, 8]

Membership testing

>>> 0 not in nums
True

Iterating over lists:

>>> for int in nums:
...     print(int)
2
4
6
8
10

List Methods

View python docs for methods of a list. Here’s a sample of some of the list methods in python:

>>> f = [10, 20, 30, 40, 50]
>>> a = f.index(50)
>>> b = f.count(0)
>>> c = f.pop()
>>> e = f.insert(2, 25)
>>> f.index(20)
1
>>> a
4
>>> b
0
>>> c
50
>>> f
[10, 20, 25, 30, 40]

Tuples

  • An ordered collection of immutable data.
  • Similar to lists except it’s elements can’t be modified and have less methods.
  • Like lists, tuples are a sequence type.
  • Can be nested, or a tuple within a tuple is permitted.
  • Tuples can be indexed, sliced, iterated, and tested for membership inclusion.

Syntax for creating tuples

a = (1, 5, 3, 10, 20, 100)

Tuples indexing

>>> a[3]
10
Tuples are immutable,so element reassignment not permitted: 
>>> a[4] =9
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment

Negative indexes

>>> a[-3]
10

Tuple Slicing

>>> a[::-2]
(100, 10, 5)

Tuple operations

>>> b = (5, 10, 15, 0, 'hey', (1, 2), [1, 2, 3])
>>> c = tuple(range(5))
>>> b in c
False
>>> b not in c
True
>>> b + c
(5, 10, 15, 0, 'hey', (1, 2), [1, 2, 3], 0, 1, 2, 3, 4)
>>> c * 2
(0, 1, 2, 3, 4, 0, 1, 2, 3, 4)

Can use the builtin tuple() function with a generator to emulate a tuple comprehension.

>>> a = tuple((i for i in range(10)))
>>> a
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

Iterating over Tuples

import random
b = tuple((random.randint(1, 1000) for x in range(5)))
# iterate over b with for loop
for x in b:
    print(x)

766
878
520
982
347

Sets

  • Sets are an unordered collection of distinct objects.
  • Sets in python are influenced by sets in mathematics.
  • Sets are popular solutions for membership testing and removing duplicates.
  • Sets are mutable like lists, so their items can be modified.
  • Sets don’t support indexing.
  • Sets don’t support slicing.
  • There’s another type of set known as frozensets which are immutable and thus hashable.

Example of Sets

>>> a = set([1, 2, 3])
>>> a
{1, 2, 3}

Example of frozensets

>>> b = frozenset([4, 'a', 10])
>>> b
frozenset({10, 4, 'a'})

Example of set operations

>>> vowels.update('o', 'u', 'y')
>>> vowels
{'a', 'i', 'o', 'u', 'y', 'e'}
>>> vowels.intersection_update(['a', 'y', 'e'])
>>> vowels
{'y', 'e', 'a'}
>>> vowels.difference_update(['a', 3, 'i'])
>>> vowels
{'y', 'e'}
>>> vowels.symmetric_difference_update(['y', 'a'])
>>> vowels
{'e'}
>>> vowels.add('a')
>>> vowels.add('a')
>>> vowels.add('e')
{'e', 'a'}
>>> vowels.discard('e')
>>> vowels
{'z', 'a'}
>>> vowels.pop()
'z'
>>> vowels.clear()
>>> vowels
set()
>>> vowels = {'a', 'e', 'i', 'o', 'u', 'y'}
>>> for letter in vowels:
        print(letter)
a
i
o
y
e

Set comprehensions

>>> {i for i in range(10)}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Dictionaries

  • Dictionaries are a builtin data structure in python that’s designed to hold key/value pairs.
  • Dictionaries are mapping types.
  • Dictionaries support indexing by keys.
  • Dictionary keys must be immutable.
  • Dictionaries are known as associative arrays in other languages.
  • There’s several derivatives of dictionaries in the python collection module.

How to create a dictionary

day = {'Mon': 1, 'Tues': 2, 'Wed': 3, 'Thurs': 4, 'Fri': 5, 'Sat': 6, 'Sun': 7}

How Indexing Works with Dictionaries

>>> auto_complete = {'a': 'amazon', 'b': 'bank of america', 'c': 'calculator'}
>>> auto_complete
{'a': 'amazon', 'b': 'bank of america', 'c': 'calculator'}

Dictionary methods

weekday = {'Mon': 1, 'Tues': 2, 'Wed': 3, 'Thurs': 4, 'Fri': 5, 'Sat': 6, 'Sun': 7}
>>> weekday.items()
dict_items([('1', 'Mon'), ('2', 'Tues'), ('3', 'Wed'), ('4', 'Thurs'), ('5', 'Fri')])
>>> weekday.keys()
dict_keys(['1', '2', '3', '4', '5'])
>>> weekday.values()
dict_values(['Mon', 'Tues', 'Wed', 'Thurs', 'Fri'])
# gets value when key is passed 
>>> weekday.get('3')
'Wed'

Iterating over dictionaries

>>> letters = {'a': 'apples', 'b': 'banana', 'c': 'coconut', 'd': 'durian'}
>>> for keys, values in letters.items():
        print(keys, values)

a apples
b banana
c coconut
d durian

Dictionary Comprehensions


>>> {k: 'a' for k in range(1, 6)}
{1: 'a', 2: 'a', 3: 'a', 4: 'a', 5: 'a'}
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.