This note mainly focuses on summarizing knowledge based on Corey Schafer’s Python Tutorial
Lists
List is a collection which is:
Creating Lists
We use square bracket notation to represent a list.
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))
|
Accessing Lists
There are two ways to access lists:
Let ls
be a list containing m elements.
Indexing
Operation |
Description |
ls[i] |
Access the i+1th element. |
ls[-i] |
Access the i to last element. |
courses = ['History', 'Math', 'Physics', 'CompSci']
print(courses[0]) print(courses[3]) print(courses[-1])
|
Slicing
Operation |
Description |
ls[i:j] |
Access elements in the location [i,j). |
ls[:j] |
Access elements in the location [0,j). |
ls[i:] |
Access elements in the location [i,m]. |
ls[:] |
Access elements in the location [0,m]. |
courses = ['History', 'Math', 'Physics', 'CompSci']
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() 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() 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)
|
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)
|
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))
|
Traversing Lists
Finding Indices
courses = ['History', 'Math', 'Physics', 'CompSci'] print('Math' in courses)
|
in
is useful in traversing.
In addition to in
, we can use index
method.
courses = ['History', 'Math', 'Physics', 'CompSci'] print(courses.index('CompSci'))
|
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:
Creating Tuples
We use parentheses notation to represent a tuple.
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.
list_1 = ['History', 'Math', 'Physics', 'CompSci'] list_2 = list_1
print(list_1) print(list_2)
list_1[0] = 'Art'
print(list_1) print(list_2)
|
['History', 'Math', 'Physics', 'CompSci'] ['History', 'Math', 'Physics', 'CompSci'] ['Art', 'Math', 'Physics', 'CompSci'] ['Art', 'Math', 'Physics', 'CompSci']
|
tuple_1 = ('History', 'Math', 'Physics', 'CompSci') tuple_2 = tuple_1
print(tuple_1) print(tuple_2)
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:
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 |
A∩B |
Find elements in both set A and B. |
union |
A∪B |
Combine set A and B. |
difference |
A∖B |
Find elements in set A and not in set B. |
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_list = [] empty_list = list()
empty_tuple = () empty_tuple = tuple()
empty_set = {} empty_set = set()
|