Codecademy Logo

Built-In Data Structures

Print Cheatsheet

Strings

A string is a sequence of characters (letters, numbers, whitespace or punctuation) enclosed by quotation marks. It can be enclosed using either the double quotation mark " or the single quotation mark '.

If a string has to be broken into multiple lines, the backslash character \ can be used to indicate that the string continues on the next line.

user = "User Full Name"
game = 'Monopoly'
longer = "This string is broken up \
over multiple lines"

String Method .lower()

The string method .lower() returns a string with all uppercase characters converted into lowercase.

greeting = "Welcome To Chili's"
print(greeting.lower())
# Prints: welcome to chili's

String Method .upper()

The string method .upper() returns the string with all lowercase characters converted to uppercase.

dinosaur = "T-Rex"
print(dinosaur.upper())
# Prints: T-REX

String Method .title()

The string method .title() returns the string in title case. With title case, the first character of each word is capitalized while the rest of the characters are lowercase.

my_var = "dark knight"
print(my_var.title())
# Prints: Dark Knight

Indexing and Slicing Strings

Python strings can be indexed using the same notation as lists, since strings are lists of characters. A single character can be accessed with bracket notation ([index]), or a substring can be accessed using slicing ([start:end]).

Indexing with negative numbers counts from the end of the string.

str = 'yellow'
str[1] # => 'e'
str[-1] # => 'w'
str[4:6] # => 'ow'
str[:4] # => 'yell'
str[-3:] # => 'low'

Python Lists: Data Types

In Python, lists are a versatile data type that can contain multiple different data types within the same square brackets. The possible data types within a list include numbers, strings, other objects, and even other lists.

numbers = [1, 2, 3, 4, 10]
names = ['Jenny', 'Sam', 'Alexis']
mixed = ['Jenny', 1, 2]
list_of_lists = [['a', 1], ['b', 2]]

Lists

In Python, lists are ordered collections of items that allow for easy use of a set of data.

List values are placed in between square brackets [ ], separated by commas. It is good practice to put a space between the comma and the next value. The values in a list do not need to be unique (the same value can be repeated).

Empty lists do not contain any values within the square brackets.

primes = [2, 3, 5, 7, 11]
print(primes)
empty_list = []

List Slicing

A slice, or sub-list of Python list elements can be selected from a list using a colon-separated starting and ending point.

The syntax pattern is myList[START_NUMBER:END_NUMBER]. The slice will include the START_NUMBER index, and everything until but excluding the END_NUMBER item.

When slicing a list, a new list is returned, so if the slice is saved and then altered, the original list remains the same.

tools = ['pen', 'hammer', 'lever']
tools_slice = tools[1:3] # ['hammer', 'lever']
tools_slice[0] = 'nail'
# Original list is unaltered:
print(tools) # ['pen', 'hammer', 'lever']

List Method .append()

In Python, you can add values to the end of a list using the .append() method. This will place the object passed in as a new element at the very end of the list. Printing the list afterwards will visually show the appended value. This .append() method is not to be confused with returning an entirely new list with the passed object.

orders = ['daisies', 'periwinkle']
orders.append('tulips')
print(orders)
# Result: ['daisies', 'periwinkle', 'tulips']

List Method .pop()

The .pop() method allows us to remove an element from a list while also returning it. It accepts one optional input which is the index of the element to remove. If no index is provided, then the last element in the list will be removed and returned.

cs_topics = ["Python", "Data Structures", "Balloon Making", "Algorithms", "Clowns 101"]
# Pop the last element
removed_element = cs_topics.pop()
print(cs_topics)
print(removed_element)
# Output:
# ['Python', 'Data Structures', 'Balloon Making', 'Algorithms']
# 'Clowns 101'
# Pop the element "Baloon Making"
cs_topics.pop(2)
print(cs_topics)
# Output:
# ['Python', 'Data Structures', 'Algorithms']

List Method .remove()

The .remove() method in Python is used to remove an element from a list by passing in the value of the element to be removed as an argument. In the case where two or more elements in the list have the same value, the first occurrence of the element is removed.

# Create a list
shopping_line = ["Cole", "Kip", "Chris", "Sylvana", "Chris"]
# Removes the first occurance of "Chris"
shopping_line.remove("Chris")
print(shopping_line)
# Output
# ["Cole", "Kip", "Sylvana", "Chris"]

Determining List Length with len()

The Python len() function can be used to determine the number of items found in the list it accepts as an argument.

knapsack = [2, 4, 3, 7, 10]
size = len(knapsack)
print(size)
# Output: 5

Tuples

Tuples are one of the built-in data structures in Python. Tuples are immutable, meaning we can’t modify a tuple’s elements after creating one, and they do not require an extra memory block like lists. Because of this, tuples are great to work with if you are working with data that won’t need to be changed in your code.

Some of the built-in methods and functions to be used with tuples are: len(), max(), min(), .index() and .count().

my_tuple = ('abc', 123, 'def', 456, 789, 'ghi')
len(my_tuple) # returns length of tuple
max(my_tuple) # returns maximum value of tuple
min(my_tuple) # returns maximum value of tuple
my_tuple.index(123) # returns the position of the value 123
my_tuple.count('abc') # returns the number of occurrences of the value 'abc'

Syntax of the Python dictionary

The syntax for a Python dictionary begins with the left curly brace ({), ends with the right curly brace (}), and contains zero or more key : value items separated by commas (,). The key is separated from the value by a colon (:).

roaster = {"q1": "Ashley", "q2": "Dolly"}

Merging dictionaries with the .update() method in Python

Given two dictionaries that need to be combined, Python makes this easy with the .update() function.

For dict1.update(dict2), the key-value pairs of dict2 will be written into the dict1 dictionary.

For keys in both dict1 and dict2, the value in dict1 will be overwritten by the corresponding value in dict2.

dict1 = {'color': 'blue', 'shape': 'circle'}
dict2 = {'color': 'red', 'number': 42}
dict1.update(dict2)
# dict1 is now {'color': 'red', 'shape': 'circle', 'number': 42}

Dictionary value types

Python allows the values in a dictionary to be any type – string, integer, a list, another dictionary, boolean, etc. However, keys must always be an immutable data type, such as strings, numbers, or tuples.

In the example code block, you can see that the keys are strings or numbers (int or float). The values, on the other hand, are many varied data types.

dictionary = {
1: 'hello',
'two': True,
'3': [1, 2, 3],
'Four': {'fun': 'addition'},
5.0: 5.5
}

Accessing and writing data in a Python dictionary

Values in a Python dictionary can be accessed by placing the key within square brackets next to the dictionary. Values can be written by placing key within square brackets next to the dictionary and using the assignment operator (=). If the key already exists, the old value will be overwritten. Attempting to access a value with a key that does not exist will cause a KeyError.

To illustrate this review card, the second line of the example code block shows the way to access the value using the key "song". The third line of the code block overwrites the value that corresponds to the key "song".

my_dictionary = {"song": "Estranged", "artist": "Guns N' Roses"}
print(my_dictionary["song"])
my_dictionary["song"] = "Paradise City"

Python dictionaries

A python dictionary is an unordered collection of items. It contains data as a set of key: value pairs.

my_dictionary = {1: "L.A. Lakers", 2: "Houston Rockets"}

Stack data structure

A Stack is a data structure that supports two basic operations: pushing a new item to the top of the stack and popping a single item from the top of the stack.

In order to implement a stack using a node class, we have to store a node that is currently referencing the top of the stack and update it during the push and pop operations.

from node import Node
class Stack:
def __init__(self, limit=1000):
self.top_item = None
self.size = 0
self.limit = limit
def push(self, value):
if self.has_space():
item = Node(value)
item.set_next_node(self.top_item)
self.top_item = item
self.size += 1
else:
print("All out of space!")
def pop(self):
if self.size > 0:
item_to_remove = self.top_item
self.top_item = item_to_remove.get_next_node()
self.size -= 1
return item_to_remove.get_value()
else:
print("This stack is totally empty.")
def peek(self):
if self.size > 0:
return self.top_item.get_value()
else:
print("Nothing to see here!")
def has_space(self):
return self.limit > self.size
def is_empty(self):
return self.size == 0

The stack data structure

A stack is a data structure that follows a last in, first out (LIFO) protocol. The latest node added to a stack is the node which is eligible to be removed first. If three nodes (a, b and, c) are added to a stack in this exact same order, the node c must be removed first. The only way to remove or return the value of the node a is by removing the nodes c and b.

Queue follows FIFO protocol

A queue is a data structure composed of nodes, which follows a first in, first out (FIFO) protocol.

This is analogous to a line at a grocery store, for which the first customer in the queue is the first to checkout.