Exercises, examples and other material relating to training module Y104. This topic is presented on public courses
If you want to work through a whole table of values, you're likely to want to store the values in a variable that can contain more that one value at a time. Python has fundamental data types of lists, tuples and dictionaries, and this module looks at lists and tuples.
|Articles and tips on this subject||updated|
|1641||Tektronix 4010 series / Python Tuples|
The Tektronix Storage Tube was a cathode ray screen across which a beam of electrons could be swept directed, leaving a trail behind it rather like the plume behind an aircraft (technology note). The technology was developed further to allow the picture generated to be held on the screen for quite ...
|4368||Shuffling a list - Ruby and Python|
Shuffling a list / array is quite a common requirement. The best way to do it is to take a list of all the items to be shuffled, and to choose one at random as the first member of the output list / array. Then move the last item on the incoming array into the gap left, and choose another from the now ...
|4027||Collections in Python - list tuple dict and string.|
All the languages that we teach have "collection" variables - single names under which a series of values is stored, keyed or indexed in some way. There are four such types in Python
Lists ... starting off with index position 0, and alterable within the stucture as the program runs. You may erroneously ...
|3763||Spike solutions and refactoring - a Python example|
Refactoring - taking a program that works (as far as it goes) and restructuring it so that it can go much further - that its code can be reusable, that it's more robust, that it can be updated to do more, and so on.
Spike Solution - an answer to a problem that can go no further, and perhaps ignores ...
|3669||Stepping through a list (or an array) in reverse order|
If you want to iterate through a list in reverse order, you can do so by stepping over (iterating through) the indexes of the list in reverse order. So in Python, for example, you would use range (or xrange for a potentially long list) with an increment of -1, giving the final index number as the start ...
|3348||List slices in Python - 2 and 3 values forms, with an uplifting example|
Python's lists are indexed collection objects. That means that they're rather like arrays in that you look up elements by their position numbers, and the number start at a fixed point (0 in the case of Python); they're not totally like arrays in that they are not stored at unchanging sequential memory ...
|3257||All possible combinations from a list (Python) or array (Ruby)|
If there are eight of us at a meeting, how many possibilities are there for a pair of people to stongly disagree? The answer turns out to be 28. And if you look at subgoups of 3, looking for everyone to have the same opinion within the subgroup, the answer is many more.
If there are eight stations ...
|3181||Beware - a=a+b and a+=b are different - Python|
It's commonly stated the the += operator is simply a more efficient and shorter to code alternative to using a + operator and saving back to the same variable ... in other words that
original += extra
original = original + extra
do the same thing.
But - in Python at least ...
|3118||Arrays of arrays - or 2D arrays. How to program tables.|
It's shorthand when you're learning a new programming language to ask "how does it handle multiple dimension arrays" ... but in practise very few languages actually support true multidimensional arrays these days, and in those which do you might be well advised to use an alternative that's more flexible.
|2996||Copying - duplicating data, or just adding a name? Perl and Python compared|
When you copy a list in Perl, you're duplicating the data and you end up with two distinct copies ... but when you copy a list in Python, you're copying the reference so that you end up with two names for the same variable - almost like an alias.
So in Perl - with two different copies - you end up with ...
|899||Python - extend v append on a list|
In Python, you can extend a list and you can append to it as well.
What's the difference? If you append a list to another list, you add the new list as a single extra list to the original, thus makingthe original list just one longer with an item that is itself a list. But if you extend a list ...
|2719||Traffic lights in Python|
A really short demo (I'm short on time ... in Dublin and rushing off to do day No. 2 of a Python course!)
A loop - an anonymous list, and a modulo function that lets us cycle round and round the members of that list
for k in range(12):
light = ["red","red-an-yellow","green","yellow"][k%4]
|657||The ternary operator in Python|
The ? : operator that you may have come across in Perl, PHP, C and Java - known as the ternary or conditional operator - is ABSENT from Python. "But it's so useful" I hear you cry. Ah yes, but isn't this elegant:
val = float(raw_input("Age: "))
status = ("working","retired")[val>65]
print "You should ...
|2368||Python - fresh examples of all the fundamentals|
Some more new examples in Python - from this week's course.
From my Introduction to Python / simple example to show the power of the language, I present my example that parsed a big data (log) file and counter and sorted by number of accesses the hits from various remote hosts. A long report, ending ...
|2284||Strings as collections in Python|
In Python, I can treat a string as a collection of characters and iterate through it without the need to do any sort of conversion on it, or muck about with "substr" ...
breakfast = "Croissants and toast"
for letter in breakfast:
print "Give me a ",letter
print "and we ...
|2280||Creating and iterating through Python lists|
In Python, you create lists by putting a series of values in square brackets - and the program creates a list with that number of elements. You can change an element by referring to the element by number in square brackets, remembering that Python starts counting at 0. Unlike Perl, you can't extend ...
|1789||Looking for a value in a list - Python|
In any scripting language, avoiding loops makes for easier to write and faster to run code. One example is Pythons if .. in construct, where you can avoid a loop to test whether a value matches any member of a list or tuple.
stuff = ["red","green","blue"]
if "green" in stuff: print ("On ...
|1220||for loop - how it works (Perl, PHP, Java, C, etc)|
When writing a program, you'll often want to repeat a block of code, counting up through a table or performing a block of code with an input value (loop counter) that goes up 1, 2, 3, 4 etc.
You COULD do this using a while loop, but this means you have to specify each of
• how to start (initialise) ...
|955||Python collections - mutable and imutable|
Should you use a list or a tuple ... or perhaps a dictionary to store a collection of objects in your Python program? To help you make the decision, think whether you need to be able to modify the collection after you've created it (mutable) or not (immutable), and whether you want it to be indexed ...
|383||Overloading of operators on standard objects in Python|
In python, everything is an object and operations performed by operators such as + and * vary in exactly what they do based on the class (type) or objects on which they're run.
If I use the * operator on a list, it replicates it ... but if I use it on an integer, it multiplies it ...
apple = 
|3slice|| List slices - 1 2 and 3 value forms|
|backuds|| Going through a list backwards|
|cally.py|| Days and months exercise - answer using methods|
|cmp.py|| Comparing lists|
|da1|| Using the power of lists to reduce loops (control)|
|daze|| Using the power of lists to reduce loops (actual)|
|dmy|| Two alternatives - day of year -> day of month and month of year|
|f2|| Copy list v Clone list|
|inlist.py|| The in operator - is a value in a list|
|lc|| List Comprehensions|
|lcopy.py|| Copying a list (or rather - copying a reference to a list)|
|li1.py|| List - first example|
|li2.py|| for loop to handle each element of a list|
|li3.py|| Use of range to give list indexes|
|li4.py|| range to go through each element of a list|
|lister|| 4 different ways of parsing a list|
|litu.py|| Converting a list to a tuple|
|lo|| list manipulation|
|lp1|| Whole list or just elements of list?|
|m2|| Alternative answer to exercise 1|
|menu.py|| A list of lists - works like a 2 D array but better ;-)|
|months|| Answer - excercise 1 - day and month numbers|
|mutt|| mutable v immutable|
|pe|| using +=|
|pf|| using + and re-assigning|
|repeat.py|| + and * operators on a list|
|revq|| Parking exercise - mk 1|
|revq2|| Parking exercise - mark 2|
|revq3|| Parking exercise - final sample answer|
|sh2.py|| Shuffle a list of numbers using supplied shuffle method|
|shuffle.py|| Shuffle a list of numbers|
|slice.py|| list slices|
|tessapy|| All possible pairs from list|
|tu1.py|| First use of a tuple|
|yuk|| some excercises with lists|
Some modules are available for download
as a sample of our material or under an Open Training Notes License
for free download from http://www.training-notes.co.uk
Why do we have collections?.
The for loop.
Working with lists and tuples.
More ways to reference elements of a list or tuple.
copying a list.
Concatenating and repeating lists and tuples.
Comparing lists and the in operator.
converting to a list or tuple.
A real live program.
Lists of lists.
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule
Well House Consultants specialise in training courses in
. We run
throughout the UK (and beyond for longer courses), and
at our training centre in Melksham, Wiltshire, England.
It's surprisingly cost effective to come on our public courses -
even if you live in a different
country or continent to us
We have a technical library of over 700 books on the subjects on which we teach.
These books are available for reference at our training centre. Also
available is the Opentalk
Forum for discussion of technical questions.