Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
 
20.9.2014 - We have just updated our course layouts and descriptions and added our 2015 schedule.

Python List, Python Tuple, Python Dictionary

If a Python list were like a pencil, then a Python Tuple would be like a pen.

Most programming languages include structures in which you can hold a collection of values. The most frequent example you'll come across is called an "array" - but exactly what that does varies from language to language as a C array is very different to a Tcl array, for example.

Python has FOUR (or five?) object types built into the language that can be regarded as collections.

LISTS AND TUPLES

Both LISTS and TUPLES consist of a number of objects which can be referenced by their position number within the object. I can create a list by writing
     salad = ["Lettuce","Tomato","Onion","Tuna"]
and then refer to salad[0] to refer to lettuce and salad[2] to refer to Onion. I can create a tuple by writing
     fruit = ("Apple","Banana","Cherry","Fig","Grapefruit")
and then refer to fruit[0] to refer to Apple, and so on. You'll notice that when I created the list I used [...] notation, and when I created the tuple I used (....) notation, but when I refer to elements later I do so using square brackets every time.

So what's the difference? With a list, I can change the elements, add extra elements, and so on, after it has been created. It's perfectly acceptable for me to write
     salad[3] = "Cheese"
for example if I want to replace the tuna. But if I write
     fruit[3] = "Orange"
I will get an error message when the program runs. You can change a list but NOT a tuple! In technical jargon, a tuple is immutable by a list is mutable.

Link - complete example using a list Link - complete example using a tuple
You're probably wondering why the two structures are provided - are they both necessary? A Tuple is much more efficient in use, and there are many occasions you want to set up a collection of objects in order (an "ordered collection") and refer to it many times later on. These days, though, with all the extra power of computers since Guido wrote Python, perhaps we could do without the tuple.

DICTIONARIES

If you don't want to refer to the elements of a collection by their position number but prefer some other type of object as a key, you can use a python dictionary. Let's see an example of one of those:
    starter = {"John":"soup", "James":"pate", "Joan":"soup"}
There are three elements in that dictionary, and I can refer to starter["James"] and get the string "pate". You'll notice that I set up a dictionary with { ... } (curly braces, but yet again I refer to it using square brackets. If you want to perform an operation on element of a dictionary, you can find out the keys using the keys method
    print starter.keys()
for example since you can't know what the elements are called just be looking at a count of the number of elements as you can with a list or tuple.

If you're familiar with Perl hashes, PHP associative arrays or Tcl arrays, then you have a good parallel to a python dictionary.

Link - complete example using a dictionary
STRINGS

Strings can be treated as immutable ordered collection objects. In other words, I can write
    something = "Marmalade"
    third = something[2]
and have the letter "r" assigned to the variable third. This is a very useful facility in certain applications - for example if you're using Python in a bioinformatics application and you're doing sequence analysis.

Link - complete example using a string as a tuple
ITERATORS

An iterator is an object that generates a collection. If you set up a large collection (for example a list that contains all ten thousand lines from a data file), you're occupying computer memory ... and if the only thing you then do with it is process each element once, it's not efficient. Increase the number of lines in the file by a factor of 10 or 100 and you're likely to find that you're starting to create "issues" on the host computer. Iterators overcome this problem. For example
    for line in huge.readlines():
will set up a temporary list containing all the data in the stream opened in object huge, then put each element into the variable line one by one. In contrast, if you write
    for line in huge.xreadlines():
then you're using an iterator and lines from the file are only read in as required.

If you want to write your own generator function, you can do so; to return an intermediate value, use the keyword yield rather than the keyword return.

Link - complete example using a generator function

See also Python programming course

Please note that articles in this section of our web site were current and correct to the best of our ability when published, but by the nature of our business may go out of date quite quickly. The quoting of a price, contract term or any other information in this area of our website is NOT an offer to supply now on those terms - please check back via our main web site

Related Material

Python - Lists and Tuples
  [4027] Collections in Python - list tuple dict and string. - (2013-03-04)
  [3763] Spike solutions and refactoring - a Python example - (2012-06-13)
  [3669] Stepping through a list (or an array) in reverse order - (2012-03-23)
  [3348] List slices in Python - 2 and 3 values forms, with an uplifting example - (2011-07-06)
  [3257] All possible combinations from a list (Python) or array (Ruby) - (2011-04-23)
  [3181] Beware - a=a+b and a+=b are different - Python - (2011-02-23)
  [3118] Arrays of arrays - or 2D arrays. How to program tables. - (2011-01-02)
  [2996] Copying - duplicating data, or just adding a name? Perl and Python compared - (2010-10-12)
  [2719] Traffic lights in Python - (2010-04-13)
  [2368] Python - fresh examples of all the fundamentals - (2009-08-20)
  [2284] Strings as collections in Python - (2009-07-12)
  [2280] Creating and iterating through Python lists - (2009-07-12)
  [1789] Looking for a value in a list - Python - (2008-09-08)
  [1641] Tektronix 4010 series / Python Tuples - (2008-05-13)
  [1220] for loop - how it works (Perl, PHP, Java, C, etc) - (2007-06-06)
  [955] Python collections - mutable and imutable - (2006-11-29)
  [899] Python - extend v append on a list - (2006-10-20)
  [657] The ternary operator in Python - (2006-03-25)
  [383] Overloading of operators on standard objects in Python - (2005-07-19)

Python - Dictionaries
  [4029] Exception, Lambda, Generator, Slice, Dict - examples in one Python program - (2013-03-04)
  [4027] Collections in Python - list tuple dict and string. - (2013-03-04)
  [3934] Multiple identical keys in a Python dict - yes, you can! - (2012-11-24)
  [3662] Finding all the unique lines in a file, using Python or Perl - (2012-03-20)
  [3555] Football league tables - under old and new point system. Python program. - (2011-12-18)
  [3554] Learning more about our web site - and learning how to learn about yours - (2011-12-17)
  [3488] Python sets and frozensets - what are they? - (2011-10-20)
  [3464] Passing optional and named parameters to python methods - (2011-10-04)
  [2994] Python - some common questions answered in code examples - (2010-10-10)
  [2986] Python dictionaries - reaching to new uses - (2010-10-05)
  [2915] Looking up a value by key - associative arrays / Hashes / Dictionaries - (2010-08-11)
  [2368] Python - fresh examples of all the fundamentals - (2009-08-20)
  [1145] Using a list of keys and a list of values to make a dictionary in Python - zip - (2007-04-13)
  [1144] Python dictionary for quick look ups - (2007-04-12)
  [955] Python collections - mutable and imutable - (2006-11-29)
  [103] Can't resist writing about Python - (2004-10-29)

Python - More on Collections and Sequences
  [3797] zip in Python - (2012-07-05)
  [3439] Python for loops - applying a temporary second name to the same object - (2011-09-14)
  [3348] List slices in Python - 2 and 3 values forms, with an uplifting example - (2011-07-06)
  [3150] Python dictionaries - mutable and immutable keys and values - (2011-01-29)
  [2996] Copying - duplicating data, or just adding a name? Perl and Python compared - (2010-10-12)
  [2920] Sorting - naturally, or into a different order - (2010-08-14)
  [2894] Sorting people by their names - (2010-07-29)
  [2718] Python - access to variables in the outer scope - (2010-04-12)
  [1873] List Comprehensions in Python - (2008-11-06)
  [1869] Anonymous functions (lambdas) and map in Python - (2008-11-04)
  [1310] Callbacks - a more complex code sandwich - (2007-08-19)
  [1304] Last elements in a Perl or Python list - (2007-08-16)
  [899] Python - extend v append on a list - (2006-10-20)
  [633] Copying a reference, or cloning - (2006-03-05)
  [386] What is a callback? - (2005-07-22)
  [61] Python is a fabulous language - (2004-09-24)

resource index - Python
Solutions centre home page

You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum.

At Well House Consultants, we provide training courses on subjects such as Ruby, Lua, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site.

Comment: "Thanks for your comment, "Anon". This article is an ..."
Visitor Ranking 3.0 (5=excellent, 1=poor)

Comment by Graham (published 2010-09-11) Suggested link.
Thanks for your comment, "Anon". This article is an overview comparison and not a definitive specification of lists, tuples and dictionaries. I never claimed it to be complete reference material ... so it's natural that it's incomplete. My suggested link includes an alternative description of Tuples, described on their own rather than based on a comparison. [#3774]

Comment by Anon (published 2010-09-11)
you have an incomplete understanding of python tuple [#3689]

You can Add a comment or ranking or edit your own comments

Average page ranking - 3.0

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/solutions/python-p ... onary.html • PAGE BUILT: Wed Mar 28 07:47:11 2012 • BUILD SYSTEM: wizard