Python Intro
List
Using the join() method to concatenate all elements in a list.
1 | list = ["this", "is", "an", "example", "of", "using", "join()", "method"] |
Using the split() method to split a string into a list.
1 | print(new_list.split(seperator)) |
Set
intersection() , difference() , union()
1 | set_1 = {1, 2, 3} |
Dictionary
Indexing VS get()
get() returns None instead of raising a KeyError if the key does not exist.
1 | dict_1 = { |
keys() , values(), items()
1 | print(dict_1.keys()) |
format()
1 | name = '4pril' |
* and **
1 | def func(*args, **kwargs): |
Comprehensions
List Comprehension
1 | nums = [1, 2, 3, 4] |
Set Comprehension
1 | nums = [1, 2, 3, 4, 5, 1, 3] |
Dictionary Comprehension
1 | name = ['Tom', 'Bob', 'Andy'] |
Generator Comprehension
1 | list = [1, 2, 3, 4, 5] |
There is a yield in square function, which means it is a generator function. when it is called, it returns a generator object .
During the for loop where calling the square function, Python actually executes logic similar to this:
1 | g = square(list) |
next() is a build-in function that retrieves the next value produced by a generator.
The first time next(g) is called, the generator runs until it reaches yield, returning 1.
The function then pauses at that position.
The next time next(g) is called, execution resumes from where it paused, so the variable num continues from 2 instead of starting again from 1.
sorted()
Preparation for data structure
1 | class Student: |
There are several ways to use sorted() function.
Using a normal function as the key.
Using lambda expression to specify the key.
Using the
attrgetter()built-in function to retrieve the attribute used for sorting.
1 | def get_name(student) |
Generator
generator is an essential feature of Python. Anyone who wants to become familiar with Python should understand how they work.
Why is generator so important ? Let’s look at the example below.
1 | '''Suppose we want to get the squeare of every number in a list, |
In this case, all values are computed at once. If there are 10,000,000 number in the list and having such large amount of values in memory would be low-efficient and redundant.
To improve efficiency, we can use a generator.
1 | def square(list): |
When using a generator, values are produced one at a time only when they are requested, instead of computing all values in advance.
The generator can also be iterated using a for loop:
1 | for num in square_numbers: |
Additionally, we can also create a generator by using parentheses.
1 | nums = (n * n for n in [1, 2, 3, 4, 5]) |
Now let’s look at the difference in memory usage and execution time between a list and a generator.
1 | import sys |









