This note mainly focuses on summarizing knowledge based on Corey Schafer’s Python Tutorial

Lists

List is a collection which is:

  • ordered
  • changeable

Creating Lists

We use square bracket notation to represent a list.

empty_list = [] # create an empty list

courses = ['History', 'Math', 'Physics', 'CompSci']
print(courses)
['History', 'Math', 'Physics', 'CompSci']

Similar to string, we can use len to get the length of the list.

courses = ['History', 'Math', 'Physics', 'CompSci']

print(len(courses))
4

Accessing Lists

There are two ways to access lists:

  • Indexing
  • Slicing

Let ls be a list containing mm elements.

Indexing

Operation Description
ls[i] Access the i+1thi+1^{th} element.
ls[-i] Access the ii to last element.
courses = ['History', 'Math', 'Physics', 'CompSci']

# Indexing
print(courses[0])
print(courses[3])
print(courses[-1]) # negative index
History
CompSci
CompSci

Slicing

Operation Description
ls[i:j] Access elements in the location [i,j)[i, j).
ls[:j] Access elements in the location [0,j)[0, j).
ls[i:] Access elements in the location [i,m][i, m].
ls[:] Access elements in the location [0,m][0, m].
courses = ['History', 'Math', 'Physics', 'CompSci']

# Slicing
print(courses[1:3])
print(courses[:2])
print(courses[2:])
print(courses[:])
['Math', 'Physics']
['History', 'Math']
['Physics', 'CompSci']
['History', 'Math', 'Physics', 'CompSci']

Modifying Lists

Adding Elements to Lists

There are some ways to add elements to lists:

Method Description
append Add a single element to the end.
insert Add a single element to the specific location.
extend Add multiple elements to the end.

Firstly, we add 'Art' to our courses.

courses = ['History', 'Math', 'Physics', 'CompSci']
courses.append('Art')
print(courses)
['History', 'Math', 'Physics', 'CompSci', 'Art']

We can also insert 'Art' to the top (i.e. the first position) of courses.

courses = ['History', 'Math', 'Physics', 'CompSci']
courses.insert(0, 'Art')
print(courses)
['Art', 'History', 'Math', 'Physics', 'CompSci']

Finally, we want to add a list of courses (e.g. 'Art' 'Education') to our courses list.

courses = ['History', 'Math', 'Physics', 'CompSci']
courses_2 = ['Art', 'Education']
courses.extend(courses_2)
print(courses)
['History', 'Math', 'Physics', 'CompSci', 'Art', 'Education']

Removing Elements From Lists

Method Description
remove Remove a specific element.
pop Remove the last element and return it.
courses = ['History', 'Math', 'Physics', 'CompSci']

courses.remove('Math')
print(courses)

popped = courses.pop() # last value
print(courses)
print(popped)
['History', 'Physics', 'CompSci']
['History', 'Physics']
CompSci

With pop method, the list can be used as a stack or a queue.

Reversing Lists

courses = ['History', 'Math', 'Physics', 'CompSci']
courses.reverse()
print(courses)
['CompSci', 'Physics', 'Math', 'History']

Sorting Lists

Using sort Method

We can sort our courses in alphabetical order.

courses = ['History', 'Math', 'Physics', 'CompSci']
courses.sort() # in alphabetical order
print(courses)
['CompSci', 'History', 'Math', 'Physics']

And we can sort a list of integers in ascending order.

nums = [1, 5, 2, 4, 3]
nums.sort()
print(nums) # in ascending order
[1, 2, 3, 4, 5]

Or we can add parameter values reverse=True to the sort method to sort nums in descending order.

nums = [1, 5, 2, 4, 3]
nums.sort(reverse=True)
print(nums) # in descending order
[5, 4, 3, 2, 1]

Using sorted Function

In addition to use sort method in list, we can use sorted function. The difference is that sorted will return a new object.

courses = ['History', 'Math', 'Physics', 'CompSci']
sorted_courses = sorted(courses)
print(sorted_courses)
['CompSci', 'History', 'Math', 'Physics']

Finding Values in Lists

min, max and sum

Function Description
min Find the minimum element.
max Find the maximum element.
sum Return the sum of all the elements.
nums = [1, 5, 2, 4, 3]
print(min(nums))
print(max(nums))
print(sum(nums))
1
5
15

Traversing Lists

Finding Indices

courses = ['History', 'Math', 'Physics', 'CompSci']
print('Math' in courses)
True

in is useful in traversing.

In addition to in, we can use index method.

courses = ['History', 'Math', 'Physics', 'CompSci']
print(courses.index('CompSci'))
3

If the value we want to find is not in list, ValueError will occur.

courses = ['History', 'Math', 'Physics', 'CompSci']
print(courses.index('Art'))
print(courses.index('Art'))
^^^^^^^^^^^^^^^^^^^^
ValueError: 'Art' is not in list

For Loops

The general syntax is: for <item> in <list>:.

We can find values only.

courses = ['History', 'Math', 'Physics', 'CompSci']
for course in courses:
print(course)
History
Math
Physics
CompSci

We can find indices and values using enumerate.

courses = ['History', 'Math', 'Physics', 'CompSci']
for course in enumerate(courses):
print(course)
(0, 'History')
(1, 'Math')
(2, 'Physics')
(3, 'CompSci')

With enumerate, we can set the starting index.

courses = ['History', 'Math', 'Physics', 'CompSci']
for course in enumerate(courses, start=1):
print(course)
(1, 'History')
(2, 'Math')
(3, 'Physics')
(4, 'CompSci')

Conversing Between Lists and Strings

For example, we want to turn courses into comma-separated string.

courses = ['History', 'Math', 'Physics', 'CompSci']
course_str = ', '.join(courses)
print(course_str)
History, Math, Physics, CompSci

Now we want to turn it back.

courses = ['History', 'Math', 'Physics', 'CompSci']
course_str = ', '.join(courses)

new_list = course_str.split(', ')
print(new_list)
['History', 'Math', 'Physics', 'CompSci']

Tuples

Tuple is a collection which is:

  • ordered
  • unchangeable

Creating Tuples

We use parentheses notation to represent a tuple.

empty_tuple = () # create an empty tuple

courses = ('History', 'Math', 'Physics', 'CompSci')
print(courses)
('History', 'Math', 'Physics', 'CompSci')

Mutable and Immutable

Lists and tuples have most methods in common.

The significant difference between list and tuple is mutability.

  • list: Mutable
  • tuple: Immutable

We use an example of list and tuple modifying elements to interpret mutability.

# Mutable
list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1

print(list_1)
print(list_2)

# Modify the list
list_1[0] = 'Art'

# Both value are modified
print(list_1)
print(list_2)
['History', 'Math', 'Physics', 'CompSci']
['History', 'Math', 'Physics', 'CompSci']
['Art', 'Math', 'Physics', 'CompSci']
['Art', 'Math', 'Physics', 'CompSci']
# Immutable
tuple_1 = ('History', 'Math', 'Physics', 'CompSci')
tuple_2 = tuple_1

print(tuple_1)
print(tuple_2)

# Modify the tuple
# Error
tuple_1[0] = 'Art'

print(tuple_1)
print(tuple_2)
tuple_1[0] = 'Art'
~~~~~~~^^^
TypeError: 'tuple' object does not support item assignment

Sets

Set is a collection which is:

  • unordered
  • unchangeable

Especially, sets allow no duplicates.

Creating Sets

We use curly braces notation to represent a tuple.

cs_courses = {'History', 'Math', 'Physics', 'CompSci'}
print(cs_courses)
{'History', 'CompSci', 'Math', 'Physics'}

The result of print changes with every execution due to sets’ unordered feature.

cs_courses = {'History', 'Math', 'Physics', 'CompSci'}
print(cs_courses)
{'Math', 'Physics', 'CompSci', 'History'}

Allowing No Duplicates

cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'CompSci', 'Math'}
print(cs_courses)
{'History', 'Math', 'Physics', 'CompSci'}

Sets Operation

Operation Notation Description
intersection ABA\cap B Find elements in both set AA and BB.
union ABA\cup B Combine set AA and BB.
difference ABA\setminus B Find elements in set AA and not in set BB.
cs_courses = {'History', 'Math', 'Physics', 'CompSci'}
art_courses = {'History', 'Math', 'Art', 'Design'}

print(cs_courses.intersection(art_courses))
print(cs_courses.union(art_courses))
print(cs_courses.difference(art_courses))
{'Math', 'History'}
{'Math', 'Physics', 'Art', 'History', 'CompSci', 'Design'}
{'Physics', 'CompSci'}

Creating Empty Lists, Tuples and Sets

We can use constructor to create lists, tuples and sets.

For sets, we can only use constructor (i.e. set()) to create an empty one.

# Empty lists
empty_list = []
empty_list = list() # list constructor

# Empty Tuples
empty_tuple = ()
empty_tuple = tuple() # tuple constructor

# Empty Sets
empty_set = {} # create a dict
empty_set = set() # set constructor