To contribute/fix, fork and edit the corresponding file here
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods;
The following table has been created by clustering multiple items based on some criteria. This is easier to internalize and deliver to maximize retention among students. Moreover, there is going to be better chance of overall engagement.
What is a list method (an attribute of a variable)? What is a list operation (a stand-alone function)? What is the difference? Get this clarified first!
Intent
Method / Operation
Description
Initialize methods
none
initialize an empty list, using a tuple, using another list
operations
[], list() or list(sequence), the = operator
bl = al initializes bl as an alias for theal list object
Access methods
[idx], .index(elem)[1] .count()[2]
index throws an exception if not present
operations
in and not in, any and all, max, min, len, sum
membership in list, all or any if element(s) is True
This brings us to an important point: there are actually two kinds of objects in Python. A mutable object exhibits time-varying behavior. Changes to a mutable object are visible through all names bound to it. Python's lists are an example of mutable objects. An immutable object does not exhibit time-varying behavior. The value of immutable objects can not be modified after they are created. They can be used to compute the values of new objects, which is how a function like string.join works. When you think about it, this dichotomy is necessary because, again, everything is an object in Python. If integers were not immutable I could change the meaning of the number '2' throughout my program.
It would be incorrect to say that "mutable objects can change and immutable ones can't", however.
Slicing
A Python slice extracts elements from an iterable based on a start and stop. It returns a iterable (or sequence) containing the extracted elements.
We take slices on many types (string, list and/or tuple) in Python.
We specify an optional start index, an optional stop index, and an optional step value (0 is not acceptable as step value).
Syntax notes. The special syntax for this operation is at first confusing. But with practice, slicing becomes easy. When we omit a value, a default is used.
[Start: Stop: Step]
Slice
Description
values[1:3]
Index 1 through index 3.
values[2:-1]
Index 2 through index one from last.
values[:2]
Start through index 2.
values[2:]
Index 2 through end.
values[::2]
Start through end, skipping ahead 2 places each time.
values[:]
Returns a copy of the list with all elements
rlist = [88, 44, 65, 68, 78, \
23, 72, 28, 50, 72, 21, 47, 27, 50, 15]
What does rlist[:-10] evaluate to?
# [88, 44, 65, 68, 78]
What does rlist[:-10:3] evaluate to?
# [88, 68]
alist = [25, 20, 25, 84, 67, 99, 96, 67,\
27, 78, 73] [-3:7:-1]
What does `alist` contain?
Pre-requisite; http://j.mp/listBenefit and https://j.mp/listComprehensions List comprehensions are concise ways to create lists. The general syntax is:
[<expression> for <item> in <sequence> if <condition>]
where the if clause is optional. For example,
mylist = [1,2,3,4,5]
yourlist = [item ** 2 for item in mylist]
print(yourlist)
# [1, 4, 9, 16, 25]
Quiz
What is printed by the following statements? Or, what is the output of the following statements?
alist = [4,2,8,6,5]
blist = [num*2 for num in alist if num%2==1]
print(blist)
An assignment to all of the elements in a tuple using a single assignment statement. Tuple assignment occurs simultaneously rather than in sequence, making it useful for swapping values. a, b, = (b, a)
Using list methods
al = [a, b] a = al.pop() b = al.pop()
List Parameters
http://j.mp/parameterThis - what is the difference between parameters and arguments?
There is no pass by value in Python. Functions arguments are always passed by reference (or object reference, to be exact). The reason that numbers don’t change even if they are passed by reference is because of their immutability.
This is very unique to the Python language in that you can do multiple assignments in the same statement. For coming up with the function for determining whether a string is a palindrome, it works quite elegantly.
Dictionary
A collection of key-value pairs that maps from keys to values. The keys can be any immutable type, and the values can be any type. Dictionaries implement the associative array abstract data type.
key: A data item that is mapped to a value in a dictionary. Keys are used to look up values in a dictionary.
key-value pair: One of the pairs of items in a dictionary. Values are looked up in a dictionary by key.
Tackle a Cloudcoder exercise http://j.mp/fromlistCC - generate a dictionary or a list of tuples.
http://j.mp/reverseDictionary
http://j.mp/friendsCC
Glossary
aliases Multiple variables that contain references to the same object.
aliasing - nicknames - multiple names for the same object
Rajesh is the name of a boy; 'Ramki' might be the name used by his close relatives; "Bondaaaa" might be the name used by his close friends; 'Ramki' and "Bondaaa" are aliases (nicknames) for Rajesh
clone To create a new object that has the same value as an existing object. Copying a reference to an object creates an alias but doesn’t clone the object.
Cloning a goat using stem cells is about duplicating what is already available
delimiter A character or string used to indicate where a string should be split.
element One of the values in a list (or other sequence). The bracket operator selects elements of a list.
index An integer variable or value that indicates an element of a list.
list A collection of objects, where each object is identified by an index. Like other types str, int, float, etc. there is also a list type-converter function that tries to turn its argument into a list.
list traversal The sequential accessing of each element in a list.
modifier A function which changes its arguments inside the function body. Only mutable types can be changed by modifiers.
mutable data type A data type in which the elements can be modified. All mutable types are compound types. Lists are mutable data types; strings are not.
mutability - > ability to mutated, to be changed, to be modified
immutability -> cannot be changed
nested list A list that is an element of another list.
object A thing to which a variable can refer.
sequence Any of the data types that consist of an ordered collection of elements, with each element identified by an index.
tuple A sequential collection of items, similar to a list. Any python object can be an element of a tuple. However, unlike a list, tuples are immutable.
Exercises
1 Runestone exercises
2. Remove duplicates. A list contains duplicate elements. How can we remove them? Some approaches may lead to the elements becoming reordered, but this is not necessary.
Exercises for Illustrative Programs
http://j.mp/butFirstCC and http://j.mp/butLastCC - iterate over a list
http://bit.ly/sumSquareCC - traverse and do a summation
http://j.mp/rightShiftCC - right shift exactly by one position
http://j.mp/rotateCC
http://j.mp/swapListCC - swap elements in a list
http://j.mp/enumListCC - manually code out the enumerate function
http://j.mp/divideTwo - divide a list into two halves
Slice Exercises - Part 0
http://j.mp/rightShiftCC - right shift exactly by one position
and http://j.mp/rotateCC
http://j.mp/divideTwo - divide a list into two halves
http://j.mp/slice51 - from repl course for Python
Given a list, cut it into two equal parts. If the length of the list is odd, leave the middle item within the first chunk, so that the first list contains one more character than the second. Now print a new list on a single row with the first and second halves swapped: second half first and the first half last.