list
is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list. This is easy to imagine if you can think of a shopping list where you have a list of items to buy, except that you probably have each item on a separate line in your shopping list whereas in Python you put commas in between them.i
and assign a value to it, say integer 5
to it, you can think of it as creating an object (i.e. instance) i
of class (i.e. type) int
. In fact, you can read help(int)
to understand this better.append
method for the list
class which allows you to add an item to the end of the list. For example, mylist.append('an item')
will add that string to the list mylist
. Note the use of dotted notation for accessing methods of the objects.mylist.field
.ds_using_list.py
):shoplist
is a shopping list for someone who is going to the market. In shoplist
, we only store strings of the names of the items to buy but you can add any kind of object to a list including numbers and even other lists.for..in
loop to iterate through the items of the list. By now, you must have realised that a list is also a sequence. The speciality of sequences will be discussed in a later section.end
parameter in the call to print
function to indicate that we want to end the output with a space instead of the usual line break.append
method of the list object, as already discussed before. Then, we check that the item has been indeed added to the list by printing the contents of the list by simply passing the list to the print
function which prints it neatly.sort
method of the list. It is important to understand that this method affects the list itself and does not return a modified list - this is different from the way strings work. This is what we mean by saying that lists are mutable and that strings are immutable.del
statement. Here, we mention which item of the list we want to remove and the del
statement removes it from the list for us. We specify that we want to remove the first item from the list and hence we use del shoplist[0]
(remember that Python starts counting from 0).help(list)
for details.ds_using_tuple.py
):zoo
refers to a tuple of items. We see that the len
function can be used to get the length of the tuple. This also indicates that a tuple is a sequence as well.new_zoo
tuple contains some animals which are already there along with the animals brought over from the old zoo. Back to reality, note that a tuple within a tuple does not lose its identity.new_zoo
by specifying new_zoo[2]
and we access the third item within the third item in the new_zoo
tuple by specifying new_zoo[2][2]
. This is pretty simple once you've understood the idiom.Tuple with 0 or 1 itemsAn empty tuple is constructed by an empty pair of parentheses such asmyempty = ()
. However, a tuple with a single item is not so simple. You have to specify it using a comma following the first (and only) item so that Python can differentiate between a tuple and a pair of parentheses surrounding the object in an expression i.e. you have to specifysingleton = (2 , )
if you mean you want a tuple containing the item2
.
Note for Perl programmersA list within a list does not lose its identity i.e. lists are not flattened as in Perl. The same applies to a tuple within a tuple, or a tuple within a list, or a list within a tuple, etc. As far as Python is concerned, they are just objects stored using another object, that's all.
d = {key1 : value1, key2 : value2 }
. Notice that the key-value pairs are separated by a colon and the pairs are separated themselves by commas and all this is enclosed in a pair of curly braces.dict
class.ds_using_dict.py
):ab
using the notation already discussed. We then access key-value pairs by specifying the key using the indexing operator as discussed in the context of lists and tuples. Observe the simple syntax.del
statement. We simply specify the dictionary and the indexing operator for the key to be removed and pass it to the del
statement. There is no need to know the value corresponding to the key for this operation.items
method of the dictionary which returns a list of tuples where each tuple contains a pair of items - the key followed by the value. We retrieve this pair and assign it to the variables name
and address
correspondingly for each pair using the for..in
loop and then print these values in the for-block.in
operator.dict
class, see help(dict)
.Keyword Arguments and DictionariesIf you have used keyword arguments in your functions, you have already used dictionaries! Just think about it - the key-value pair is specified by you in the parameter list of the function definition and when you access variables within your function, it is just a key access of a dictionary (which is called the symbol table in compiler design terminology).
in
and not in
expressions) and indexing operations, which allow us to fetch a particular item in the sequence directly.ds_seq.py
):shoplist[0]
fetches the first item and shoplist[3]
fetches the fourth item in the shoplist
sequence.shoplist[-1]
refers to the last item in the sequence and shoplist[-2]
fetches the second last item in the sequence.shoplist[1:3]
returns a slice of the sequence starting at position 1, includes position 2 but stops at position 3 and therefore a slice of two items is returned. Similarly, shoplist[:]
returns a copy of the whole sequence.shoplist[:-1]
will return a slice of the sequence which excludes the last item of the sequence but contains everything else.ds_reference.py
):Note for Perl programmersRemember that an assignment statement for lists does not create a copy. You have to use slicing operation to make a copy of the sequence.
format
method!str
. Some useful methods of this class are demonstrated in the next example. For a complete list of such methods, see help(str)
.ds_str_methods.py
):startswith
method is used to find out whether the string starts with the given string. The in
operator is used to check if a given string is a part of the string.find
method is used to locate the position of the given substring within the string; find
returns -1 if it is unsuccessful in finding the substring. The str
class also has a neat method to join
the items of a sequence with the string acting as a delimiter between each item of the sequence and returns a bigger string generated from this.