Tutorial #1: Python Data Structures Cheat Sheet

Python Data Structures Cheat Sheet

Python Data Structures Cheat Sheet Secrets!

Complete Python Bootcamp From Zero to Hero in Python (Arithmetic)

Python 3 Variables

Rules:

  1. Names cannot start with a number.
  2. Names can not contain spaces, use _ instead
  3. Names can not contain any of these symbols: ‘”,<>/?|\()!@#$%^&*~-+
  4. Best practice (PEP8) that names are lowercase with underscores.
  5. Avoid using the characters ‘l’ (lowercase letter el) and Avoid using the characters ‘O’ (uppercase letter oh) as they can be confused with 1 and 0
  6. Avoid using reserved words like “list” and “str”

Python Data Structures Cheat Sheet Formula!

Assigning Variables

Reassigning Variables

Determining variable type

  1. int (for integer)
  2. float
  3. str (for string)
  4. list
  5. tuple
  6. dict (for dictionary)
  7. set
  8. bool (for Boolean True/False)

Python 3 Strings

String formatting lets you inject items into a string rather than trying to chain items together using commas or string concatenation

String Indexing

String Properties

Basic Built-in String Methods

Python 3 String Formatting

Formatting with placeholders

Format Conversion Methods

Padding and Precision of Floating

Multiple Formatting

Formatting with the .format() method

Inserted objects can be assigned keywords

Contents

1. Basics

1.1 Basic Arithmetic

1.2 Variables

1.1.1 Assigning Variables

1.1.2 Reassigning Variables

1.1.3 Determining variable type

1.3 Strings

1.3.1 String Indexing

1.3.2 String Properties

1.3.3 Basic Built-in String methods

1.4 String Formatting

1.4.1 Formatting with placeholders

1.4.2 Format conversion methods

1.4.3 Padding and Precision of Floating Point Numbers

1.4.4 Multiple Formatting

1.4.5 Formatting with the .format() method

1.4.6 Inserted objects can be assigned keywords

1.4.7 Alignment, padding and precision with .format()

1.4.8 Formatted String Literals (f-strings)

1.5 Lists

1.5.1 Indexing and Slicing

1.5.2 Basic List Methods

1.5.3 Nesting Lists

1.6 Dictionaries

1.6.1 Constructing a Dictionary

1.6.2 Nesting with Dictionaries

1.6.3 Dictionary Methods

1.7 Tuples

1.7.1 Basic Tuple Methods

1.7.2 Tuple Immutability

1.8 Sets

1.9 Booleans

1.10 Files

1.10.1 Opening and Reading a file

1.10.2 Writing to a File

1.10.3 Appending to a File

1.10.4 Iterating through a File

1.10.5 Creating new file with content

1.1 Basic Arithmetic

# Addition

print(2+1)

# output: 3

# Subtraction

print(2-1)

# output: 1

# Multiplication

print(2*2)

# output: 4

# Division

print(3/2)

# output: 1.5

# Floor Division

print(7//4)

# output: 1

# Modulo

print(7%4)

# output: 3

# Powers

print(2**3)

# output: 8

# Order of Operations

print(2 + 10 * 10 + 3)

# output: 105

# Parentheses to specify orders

print((2+10) * (10+3))

# output: 156

1.2 Variables

Rules:

1. Names cannot start with a number.

2. Names can not contain spaces, use _ instead

3. Names can not contain any of these symbols: ‘”,<>/?|\()!@#$%^&*~-+

4. Best practice (PEP8) that names are lowercase with underscores.

5. Avoid using the characters ‘l’ (lowercase letter el) and Avoid using the characters ‘O’ (uppercase letter oh) as they can be confused with 1 and 0

6. Avoid using reserved words like “list” and “str”

1.1.1 Assigning Variables

my_dogs = 2

print(my_dogs)

# output: 2

my_dogs = [‘Sammy’, ‘Frankie’]

print(my_dogs)

# output: [‘Sammy’, ‘Frankie’]

a = 5

print(a+a)

# output: 10

a = 10

print(a)

# output: 10

1.1.2 Reassigning Variables

a = 10

a = a + a

print(a)

# output: 20

a = 10

a = a + 10

a += 10

print(a)

# output: 30

a = 10

a = a + 10

a += 10

a *= 2

print(a)

# output: 60

1.1.3 Determining variable type with type()

  • int (for integer)
  • float
  • str (for string)
  • list
  • tuple
  • dict (for dictionary)
  • set
  • bool (for Boolean True/False)

a = 10

print(type(a))

# output: int

a = 31.1

print(type(a))

# output: float

a = (1, 2)

print(type(a))

# output: tuple

# variables make calculations more readable and easier to follow

my_income = 100

tax_rate = 0.1

my_taxes = my_income*tax_rate

print(my_taxes)

# output: 10.0

1.3 Strings

String formatting lets you inject items into a string rather than trying to chain items together using commas or string concatenation

1.3.1 String Indexing

print(len(‘abcd efgh’))

# output: 9

mystring = ‘abcd efgh’

print(mystring)

# output: abcd efgh

mystring = ‘abcdefghijk’

print(mystring[0])

# output: a

print(mystring[1])

# output: b

# get last letter

print(mystring[-1])

# output: k

# remove last letter

print(mystring[:-1])

# output: abcdefghij

print(mystring[-2])

# output: j

print(mystring[2:])

# output: cdefghijk

print(mystring[:2])

# output: ab

print(mystring[2:5])

# output: cde

print(mystring[1:3])

# output: bc

print(mystring[::2])

# output: acegik

print(mystring[::3])

# output: adgj

# print a string backwards

print(mystring[::-1])

# output: kjihgfedcba

1.3.2 String Properties

mystring = ‘ abcd efgh’

# concatenate

mystring = mystring + ‘ concatenate me!’

print(mystring)

# output: abcd efgh concatenate me!

letter = ‘z’

print(letter*10)

# output: zzzzzzzzzz

1.3.3 Basic Built-in String methods

mystring = ‘ abcd efgh’

mystring = mystring + ‘ concatenate me!’

# upper case the string

print(mystring.upper())

# output: ABCD EFGH CONCATENATE ME!

# lower case the string

mystring = ‘ ABCD EFGH’

mystring = mystring + ‘ concatenate me!’

print(mystring.lower())

# output: abcd efgh concatenate me!

# split string and remove a specific element

mystring = ‘Hello World’

mystring = mystring + ‘ concatenate me!’

print(mystring.split(‘W’))

# output: [‘Hello ‘, ‘orld concatenate me!’]

1.4 String Formatting

player = ‘Thomas’

points = 33

# concatenation

print(‘Last night, ‘+player+’ scored ‘+str(points)+’ points.’)

# output: Last night, Thomas scored 33 points.

# string formatting

print(f’Last night, {player} scored {points} points.’)

# output: Last night, Thomas scored 33 points.

1.4.1 Formatting with placeholders

print(“I’m going to inject %s here.” %’something’)

# output: I’m going to inject something here.

print(“I’m going to inject %s text here, and %s text here.” %(‘some’,’more’))

# output: I’m going to inject some text here, and more text here.

x, y = ‘some’, ‘more’

print(“I’m going to inject %s text here, and %s text here.”%(x,y))

# output: I’m going to inject some text here, and more text here.

1.4.2 Format conversion methods

print(‘He said his name was %s.’ %’Fred’)

# output: He said his name was Fred.

print(‘He said his name was %r.’ %’Fred’)

# output: He said his name was ‘Fred’.

print(‘I once caught a fish %s.’ %’this \tbig’)

# output: I once caught a fish this big.

print(‘I once caught a fish %r.’ %’this \tbig’)

# output: I once caught a fish ‘this \tbig’.

print(‘I wrote %s programs today.’ %3.75)

# output: I wrote 3.75 programs today.

print(‘I wrote %d programs today.’ %3.75)

# output: I wrote 3 programs today.

1.4.3 Padding and Precision of Floating

print(‘Floating point numbers: %5.2f’ %(13.144))

# output: Floating point numbers: 13.14

print(‘Floating point numbers: %1.0f’ %(13.144))

# output: Floating point numbers: 13

print(‘Floating point numbers: %1.5f’ %(13.144))

# output: Floating point numbers: 13.14400

print(‘Floating point numbers: %10.2f’ %(13.144))

# output: Floating point numbers: 13.14

print(‘Floating point numbers: %25.2f’ %(13.144))

# output: Floating point numbers: 13.14

1.4.4 Multiple Formatting

print(‘First: %s, Second: %5.2f, Third: %r’ %(‘hi!’,3.1415,’bye!’))

# output: First: hi!, Second: 3.14, Third: ‘bye!’

1.4.5 Formatting with the .format() method

print(‘This is a string {}’.format(‘INSERTED’))

# output: This is a string INSERTED

print(‘The {} {} {}’.format(‘fox’, ‘brown’, ‘quick’))

# output: The fox brown quick

print(‘The {2} {1} {0}’.format(‘fox’, ‘brown’, ‘quick’))

# output: The quick brown fox

print(‘The {0} {0} {0}’.format(‘fox’, ‘brown’, ‘quick’))

# output: The fox fox fox

1.4.6 Inserted objects can be assigned keywords

print(‘The {q} {b} {f}’.format(f=’fox’, b=’brown’, q=’quick’))

# output: The quick brown fox

print(‘First Object: {a}, Second Object: {b}, Third Object: {c}’.format(a=1,b=’Two’,c=11.3))

# output: First Object: 1, Second Object: Two, Third Object: 11.3

print(‘A %s saved is a %s earned.’ %(‘penny’,’penny’))

# output: A penny saved is a penny earned.

print(‘A {p} saved is a {p} earned.’.format(p=’penny’))

# output: A penny saved is a penny earned.

print(‘The {f} {f} {f}’.format(f=’fox’, b=’brown’, q=’quick’))

# output: The fox fox fox

result = 100/777

print(“The result was {r}”.format(r=result))

# output: The result was 0.1287001287001287

print(“The result was {r:1.5f}”.format(r=result))

# output: The result was 0.12870

# round the result

result = 100/777

print(“The result was {r:1.2f}”.format(r=result))

# output: The result was 0.13

# two-decimal number

result = 104.12345

print(“The result was {r:1.2f}”.format(r=result))

# output: The result was 104.12

name = ‘Sam’

age = 3

print(f'{name} is {age} years old.’)

# output: Sam is 3 years old.

1.4.7 Alignment, padding and precision with .format()

print(‘{0:8} | {1:9}’.format(‘Fruit’, ‘Quantity’))

print(‘{0:8} | {1:9}’.format(‘Apples’, 3.))

print(‘{0:8} | {1:9}’.format(‘Oranges’, 10))

# output:

Fruit | Quantity

Apples | 3.0

Oranges | 10

1.4.8 Formatted String Literals (f-strings)

name = ‘Fred’

print(f’He said his name is {name}.’)

# output: He said his name is Fred.

name = ‘Fred’

print(f’He said his name is {name!r}’)

# output: He said his name is ‘Fred’

num = 23.45678

print(“My 10 character, four decimal number is:{0:10.4f}”.format(num))

print(f”My 10 character, four decimal number is:{num:{10}.{6}}”)

# output:

My 10 character, four decimal number is: 23.4568

My 10 character, four decimal number is: 23.4568

num = 23.45

print(“My 10 character, four decimal number is:{0:10.4f}”.format(num))

print(f”My 10 character, four decimal number is:{num:{10}.{6}}”)

# output:

My 10 character, four decimal number is: 23.4500

My 10 character, four decimal number is: 23.45

num = 23.45

print(“My 10 character, four decimal number is:{0:10.4f}”.format(num))

print(f”My 10 character, four decimal number is:{num:10.4f}”)

# output:

My 10 character, four decimal number is: 23.4500

My 10 character, four decimal number is: 23.4500

1.5 Lists

Unlike strings, they are mutable, meaning the elements inside a list can be changed!

1.5.1 Indexing and Slicing

# Assign a list to variable

my_list = [‘one’, ‘two’, ‘three’, 4, 5, 6, 7, 8]

print(len(my_list))

# output: 8

# Grab element at index 0

print(my_list[0])

# output: one

print(my_list[1:])

# output: [‘two’, ‘three’, 4, 5, 6, 7, 8]

print(my_list[:3])

# output: [‘one’, ‘two’, ‘three’]

# add new lists

another_list = [‘nine’, ‘ten’]

new_list = my_list + another_list

print(new_list)

# output: [‘one’, ‘two’, ‘three’, 4, 5, 6, 7, 8, ‘nine’, ‘ten’]

# change element at index 0 with new value

new_list[0] = ‘ONE’

print(new_list)

# output: [‘ONE’, ‘two’, ‘three’, 4, 5, 6, 7, 8, ‘nine’, ‘ten’]

1.5.2 Basic List Methods

# Append (this is permanent!)

mylist = [1, 2, 3]

mylist.append(‘append me!’)

print(mylist)

# output: [1, 2, 3, ‘append me!’]

# Pop off the 0 indexed item

mylist.pop(0)

print(mylist)

# output: [2, 3, ‘append me!’]

# Assign the popped element, remember default popped index is -1

popped_item = mylist.pop()

print(popped_item)

# output: append me!

# show the remaining items

print(mylist)

# output: [2, 3]

new_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

# Use reverse to reverse order (this is permanent!)

new_list.reverse()

print(new_list)

# output: [‘e’, ‘d’, ‘c’, ‘b’, ‘a’]

# alphabetical order

new_list.sort()

print(new_list)

# output: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

1.5.3 Nesting Lists

# make three lists

my_list_1 = [1, 2, 3]

my_list_2 = [4, 5, 6]

my_list_3 = [7, 8, 9]

# Make a list of lists to form a matrix

matrix = [my_list_1, my_list_2, my_list_3]

print(matrix)

# output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]

# Grab first item in matrix object

print(matrix[0])

# output: [1, 2, 3]

# Grab first item of the first item in the matrix object

print(matrix[0][0])

# output: 1

# Build a list comprehension by deconstructing a for loop within a []

first_col = [row[0] for row in matrix]

print(first_col)

# output: [1, 4, 7]

1.6 Dictionaries

1.6.1 Constructing a Dictionary

# Make a dictionary with {} and : to signify a key and a value

my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}

print(my_dict[‘key2’])

# output: value2

my_dict = {‘key1’: 123, ‘key2’: [12, 23, 33], ‘key3’: [‘item0’, ‘item1’, ‘item2’]}

print(my_dict[‘key3’])

# output: [‘item0’, ‘item1’, ‘item2’]

# add key and value

my_dict[‘key4’] = ‘Al Ardosa’

print(my_dict)

# output: {‘key1’: 123, ‘key2’: [12, 23, 33], ‘key3’: [‘item0’, ‘item1’, ‘item2’], ‘key4’: ‘Al Ardosa’}

print(my_dict[‘key3’][0])

# output: item0

print(my_dict[‘key3’][0].upper())

# output: ITEM0

animal = {}

animal[‘dog’] = ‘bulldog’

animal[‘age’] = 3

print(animal)

# ouput: {‘dog’: ‘bulldog’, ‘age’: 3}

1.6.2 Nesting with Dictionaries

nest_dict = {‘key1’: {‘nest_key’: {‘sub_nest_key’: ‘value’}}}

print(nest_dict[‘key1’][‘nest_key’][‘sub_nest_key’])

# output: value

1.6.3 Dictionary Methods

# return a list of all keys only

dict = {‘key1’: 1, ‘key2’: 2, ‘key3’: 3}

print(dict.keys())

# dict_keys([‘key1’, ‘key2’, ‘key3’])

# return a list of all values only

print(dict.values())

# dict_values([1, 2, 3])

# return a list of all items

print(dict.items())

# dict_items([(‘key1’, 1), (‘key2’, 2), (‘key3’, 3)])

1.7 Tuples

Tuples are very similar to lists, however, unlike lists they can not be changed. You would use tuples that shouldn’t be changed, such as days of the week, or dates on a calendar.

1.7.1 Basic Tuple Methods

mytuple = (1, 1, 2, 3, ‘a’)

mylist = [1, 2, 3]

print(type(mytuple))

print(type(mylist))

print(mytuple.count(1))

print(len(mytuple))

print(mytuple)

print([0])

print([-1])

print(mytuple.index(‘a’))

# output:

tuple

list

2

5

(1, 1, 2, 3, ‘a’)

[0]

[-1]

4

1.7.2 Tuple Immutability

mylist[0] = ‘change’

# allowable to change if list

mytuple[0] = ‘change’

# not allowable to change if tuple

# output: mytuple[0] = ‘change’ TypeError: ‘tuple’ object does not support item assignment

1.8 Sets

Sets only show unique elements and no repetition

myset = set()

myset.add(1)

print(myset)

# output: {1}

# Add a different element

myset.add(2)

print(myset)

# output: {1, 2}

# Create a list with repeats

myset_list = [1, 1, 2, 2, 3, 4, 5, 6, 1, 1, 7, 7, 7, 8, 8, 8, 8]

print(set(myset_list))

# output: {1, 2, 3, 4, 5, 6, 7, 8}

1.9 Booleans

Booleans predefined True and False displays that are basically just the integers 1 and 0).

print(type(False))

# output: bool

print(type(True))

# output: bool

print(1 > 2)

# output: False

print(1 == 1)

# output: True

1.10 Files

mode=’r’ is read only

mode=’w’ is overwrite the files or create new

mode=’a’ is append or add to existing file

mode=’r+’ is reading and writing

mode=’w+’ is writing and reading overwriting or creates new file

1.10.1 Opening and Reading a file

myfile = open(‘myfile.txt’)

print(myfile.read())

# output: ‘The quick’ brown fox jumps over the lazy dog

myfile.seek(0)

print(myfile.readlines())

# output: [“‘The quick’ brown fox jumps over the lazy dog”]

# it is always good practice to close it.

myfile.close()

with open(‘myfile.txt’, mode=’r’) as myfile:

contents = myfile.read()

print(contents)

# output:

This is a new line

This is text being appended to test.txt

And another line here.

1.10.2 Writing to a File

# w+ which stands for write.

myfile = open(‘myfile.txt’, ‘w+’)

# Write to the file

myfile.write(‘This is a new line’)

# Read the file

# reset the reading

myfile.seek(0)

myfile.read()

myfile.close()

# output. check your ‘myfile.txt’

# appending or adding text to existing file

with open(‘myfile.txt’, mode=’a’) as myfile:

myfile.write(‘\nFourth’)

myfile.close()

# then reading the existing file

with open(‘myfile.txt’, mode=’r’) as myfile:

print(myfile.read())

myfile.close()

# output:

First

Second

Third

Fourth

1.10.3 Appending to a File

myfile = open(‘myfile.txt’, ‘a+’)

myfile.write(‘\nThis is text being appended to test.txt’)

myfile.write(‘\nAnd another line here.’)

# reset the reading

myfile.seek(0)

print(myfile.read())

myfile.close()

# output:

This is a new line

This is text being appended to test.txt

And another line here.

1.10.4 Iterating through a File

for myline in open(‘myfile.txt’):

print(myline)

# output:

This is a new line

This is text being appended to test.txt

And another line here.

with open(‘myfile.txt’) as my_new_file:

contents = my_new_file.read()

print(contents)

# output:

This is a new line

This is text being appended to test.txt

And another line here.

1.10.5 Creating new file with content

# create new file and content

with open(‘created_newfile.txt’, mode=’w’) as myfile:

myfile.write(‘I created this file’)

myfile.close()

# read the new file and it’s content

with open(‘created_newfile.txt’, mode=’r’) as myfile:

print(myfile.read())

myfile.close()

Python Data Structures Cheat Sheet
Tagged : / / / / / / / / / / / / / / / /
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x