This is the lecture note of CS61A - Lecture 10.
Lists
List is a built-in data type in Python.
1 | # Lists |
Lists are containers which can contain other values, and their values can represent collections of other values.
You can use built-in operators in
to test whether an element appears in a compound value.
1 | # Containers |
For Statements
We've written lots of code using while loops. Now, it's time to turn to an alternative way of iteration structure —— for loops.
The for statement is a way of iterating over sequences.
1 | # while statement |
Sequence Unpacking
There is a cool feature in Python's for statement: sequence unpacking.
Here is an example:
1 | def count_same(pairs): |
⚠️ Attention: This feature only works for a sequence of fixed-length sequences, such as sequence pairs.
Ranges
Range is another sequence type.
Let's see two examples of range usage.
1 | # Example 1 |
List Comprehensions
List comprehension is a powerful form of combination in the Python language.
1 | # List comprehensions |
1 | def divisors(n): |
Strings
For String, you can use either single quotation mark or double quotation mark. The only difference is that double quoted String can have multiple lines, while single quoted String can only have one line.
1 | >>> 'curry = lambda f: lambda x: lambda y: f(x, y)' |
Slicing
Slicing is an operation that you can perform on sequences such as lists and ranges.
1 | # examples of slicing |
Examples
- Question 1: Recursive Sum
1 | def my_sum(L): |
- Question 2: String Reversal
1 | def reverse(str): |
Processing Container Values
1 | # examples of sum |
1 | # examples of max |
1 | # examples of all |