List and Tuple
Sequences in Python:
Common:
Different:
- as reference
- as iterable
- list as mutable vs. tuple as immutable
- list
- tuple
string
What is list and tuple
What is list and tuple:
An informal understanding:
list and tuple are the sequential organization of elements.
An intuitive understanding:
Enclosing elements with [] to create a list.
Enclosing elements with () to create a tuple.
L = [1,2,3,4,5,6,7,8,9]
T = (1,2,3,4,5,6,7,8,9)list and tuple are sequence structures:
you can randomly access elements using subscriptor [].
Common as reference:
list/tuple is not "list"/"tuple":
it points to (or references technically) the location where the actual list/tuple is stored.
The arrows below illustrate what "points to" means.
Actually, every variable in Python is reference.
Common as reference:
When you assignment a list/tuple to another, you are actually assigning the reference (or shallow copy technically).
Changes on the "new" list would have the effect on the "old" list
Changes cannot be made on tuple (to be discussed later on).
Extra, A Quicker Way to Create a list/tuple:
You may apply list comprehensions (listcomps) to create a list, or generator expressions (genexps) to create other sequence types. This saves time and sometimes makes your code more readable.
Below is the example of doing such:
Common as iterable:
There is much convenient syntax in Python for iterables like:
L = [1,2,3,4,5,6,7,8,9]
for x in L:
print(x)We briefly introduce two built-in syntax for iterables here:
- slice operation
- map/filter/reduce
Common as iterable, slice operation:
slice operation is used to extract elements from iterables and is denoted by [] right after iterables.
A slicer takes three arguments and returns an object of the same type as, as well as a hard copy of the object being sliced:
aList = List[beg_idx:end_idx:step]
beg_idx is the position of the first element that will be taken,
end_idx is the position where you end up slicing and won't take,
step indicates how you "walk" from beg_idx to end_idx.
Extra, the detailed syntax for slice:
aList = List[beg_idx:end_idx:step]
Index can be negative, in which case they represents the position counting from the last element. The last element is represented by -1. x and x - len(seq) (-1 < x < len(seq)) represents the same position.
step represents the gap between the elements you would take, starting from beg_idx until meeting or passing end_idx. It also determines how you meet or pass end_idx. If step is positive, you have meet or pass end_idx forward, otherwise backward.
Default arguments for three parameters can be complicated and won't be covered here. However, some common cases are shown in next slide. Don't mix subscriptor [] with slicing. Subscripting returns an element while slicing returns a sequence of elements
Common as iterable, slice operation:
Common as iterable, map/filter/reduce:
These are three functions that facilitate functional approach to programming. They allow you to write neat code with less loop and branch statements.
All of them take a function and an iterable as arguments. The function argument will be applied on the elements of the iterable. Then the result (if there is) will be returned.
map(func, iterable)
filter(func, iterable)
reduce(func, iterable, [initial])
We will briefly go through these three functions, using example.
Common as iterable, map/filter/reduce:
map(func, iterable)
All elements in L increment by 1. What map() function does is:
make a hard copy of the iterable
apply add1() on each element of the hard copy
return the map object containing the information of this copy
Note that we need to cast map object to sequence (list here)
Common as iterable, map/filter/reduce:
filter(func, iterable)
All the odd elements are filtered. What filter() function does is:
make a hard copy of the iterable
filter the elements of the hard copy that don't satisfy even()
return the map object containing the information of this copy
Note that we need to cast map object to sequence (tuple here)
Common as iterable, map/filter/reduce:
reduce(func, iterable, [initial])
Putting aside initial, what reduce() is to reduce the iterable to a single value. Since func in reduce() takes two arguments and it is likely that iterable has zero element, therefore initial acts as a guarantee that there is at least one element to reduce. You may think of initial as an element that is inserted at the beginning of the iterable.
reduce() is a little bit different from map() and filter():
Before you use it, you have to import reduce from functools
func() in reduce takes two arguments and return one value
There is an optional parameter called inital
Common as iterable, map/filter/reduce:
reduce(func, iterable, [initial])
What reduce() does is:
take 1st and 2nd (if any) element, apply add() to get a value
take this value and one more element to apply add()
repeat above step until there is no more element
return the final value
Extra, lambda expression:
There is a more concise way to use map/filter/reduce, see below:
Lambda expression is anonymous function with compact syntax. It can help you write a neat code
Different, list as mutable vs. tuple as immutable:
Speaking of mutable or immutable in Python,
we are concerned with reference.
Every variable in Python, including list and tuple, is a reference. Instead of being the data itself, a reference points to the location where the data is stored. We manipulate with data via the reference.
When assigning one variable to another, we are actually making these two variables reference the same location.
Different, list as mutable vs. tuple as immutable:
list as mutable:
The content and the size of the location that a list references can be changed.
list supports adding/removing/modifying elements
This is the reason why demos in previous slides are mostly done with list, instead of tuple
Different, list as mutable vs. tuple as immutable:
list as mutable, adding elements:
There are a number of ways to add elements into a list:
list.append(element)
list.extend(ls)
list.insert(pos, element)
Note that element in a list is reference. References can point to objects of different type. Therefore, a list can hold "elements" seemingly of different types (but they are actually references !).
Different, list as mutable vs. tuple as immutable:
list as mutable, adding elements:
list.append(ele) adds an element to the end of the original list,
list.extend(ls) takes a list as argument and adds all the elements in ls to the end of the original list
list.insert(idx, ele) adds an element right after the idx-th element of the original list
Different, list as mutable vs. tuple as immutable:
list as mutable, removing elements:
list.remove(ele) removes the first element that has the same value as ele. It removes an element by value.
list.pop(idx=0) removes the idx-th element in the list. It removes an element by index.
del(list[idx]) removes the idx-th element in the list. It removes an element by index.
Different, list as mutable vs. tuple as immutable:
list as mutable, modifyng elements:
Using subscriptor [] to modify elements
Using slice operation to modify elements
Different, list as mutable vs. tuple as immutable:
tuple as immutable:
The content and the size of the location that a list references cannot be changed.
tuple does not support adding/deleting/changing elements
CS1302 Lecture 6 Chapter 10
By Chung Chan
CS1302 Lecture 6 Chapter 10
- 120