To contribute/fix, fork and edit the corresponding file
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;
Advanced list processing - list comprehension
For last section of Unit 4, Illustrative Programs, please see
Pre-requisite: (Needs updation)
Refer to the below to become familiar with the terms relevant to this unit
I just scored 63% on @realpython's "Python Lists and Tuples" quiz. What's your score? #pythonquiz
Concept Map
A picture is worth a 1000 words
mutableList
Sequences and attributes
Here are some important methods that are associated with tuple, list and dictionary - all types that are covered in Unit 4.
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
take out from specified index, or element or all elements
ordering.reverse()[9], .sort()[10]
rearrange elements in the list
operations
del, sorted
same effect as the methods with better performance?
Allocate methods
.copy()[11],[:], [s:s:s], repetition (using *) and concatenation (using +)
Create distinct list objects by duplicating existing ones
operations
slice(start, stop, step), zip, enumerate, cloning (copy.copy and deepcopy) and list comprehension
same as slice operator [], zip creates a new list with tuples from two lists, enumerate provides list with (index, element) tuple
List indexing
List Mutability
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?
Slicing of Lists
List Comprehension
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)
http://j.mp/enumListCC - manually code out the enumerate function
Find the output for these list comprehensions
Complete the code snippet to loop through the list in reverse and then print it out.
pylist = ['n', 'o', 'h', 't', 'y', 'p']
for c in ???(???):
???(c)
Eight Ways to copy/clone a list?
Using functions/operations
Use slicing - bl = al[:] (apparently, the fastest technique)
Use list comprehension bl = [elem for elem in al ]
Use list() function
Using methods 4. Use the .copy method - bl = al.copy() 5. Using .extend method 6. Using .append method
Using modules 7. Use the copy.copy function 8. Use the copy.deepcopy function
Four ways to reverse a list
Use reversemethod - al.reverse()
Use slice al = al[::-1]
Can you useslice to reverse the list, in place?
Use reversed function - list (reversed(al))
Write your own reverseList function using a loop
Four ways to swap 2 values
Use a temp variable
temp = a a = b b = temp
Use addition and subtraction
a = a + b b = a - b
a = a - b
Using XOR
a ^= b b ^= a a ^= b
Using tuple assignments
tuple assignment
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.
Sequence Assignment, Packing, Unpacking
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
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
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.
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 abstract data type.
1
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.