Python Tales - The Python Tutor Blog

A Python Programming Blog, from a Pythoneer to Pythoneers, created by The Python Tutor.

Saturday, May 13, 2017

A Tale on Python List and Functions I

Hello my Pythoneers, in this entry I’m going to talk (with some examples) about Python List and how you can combine the Built-in Python Functions Map, Reduce and Filter to create awesome functions (Well not awesome I mean great functions).
So let’s get started in here; Python List is a Data Type Built-in with Python, that means they already comes with the Python installation. This Data Type is one of the Data Types that works as a sequence, that is a set of values in a sequence, being Python dynamically typed you can create sequences of every data type value, such as Integers, Float, Strings, but also you can create sequences of custom data types such as Python Objects, but that’s not all, you can have a List of Lists also, and even a list of Dictionaries (Which we’ll discuss in later entries), and even better as Python being dynamically types you can have in the List different kinds of values, that is you can have in the same List a mix between Strings, Integers and Floats; Well this is not very useful, you rather stay with the same data type, but imagination is the only limit when you are working with Lists to solve problems.
But first things first, how do we define a Python List? Well there are several ways, we are going to start by using the square brackets signs [ ].
>>> firstList = []

In this example we use a descriptive variable using camelCase format, firstList, you can have this kind of practice for a start, highly recommended, eventually you are going to have too much variables in the same context, you won't remember which one does what if you don't make a descriptive name. Well getting back to Python List, as you can see we created a Python Statement using the assignment operator, initializing a variable called firstList as an empty List.
You can also initialize Python List using the Built-in function called List (this is a reserved word of the Python Programming Language).

>>> firstList = List()

So now that we know this, what else? Well we can also initialize with default values, but one thing that you must keep in mind is that in sequences, each values is separated with comma, this is the default argument separator character (remember this).

>>> secondList = [1, 2, 3, 4, 5]

Great, as we can see we can create a list with default values, but what about if I want to insert new elements inside this list? Well now we use a List method, Method? What is a method? A method is a function that is built with the data type, this is a concept that we can cover in detail later in Python Object Oriented entries but for now I can say you can use a method by placing a dot (.) after the variable a calling the method name. For the case we want to add a new value to the sequence, we can use the append method, like this

>>> secondList = [1, 2, 3, 4, 5]
>>> secondList.append(6)
>>> secondList
[1, 2, 3, 4, 5, 6]

Pretty cool right? One thing you must keep in mind, is that some methods produces changes inside the variable (also called mutators), other methods return values (acting like a function), and other methods combine this last two, they change values inside the variable and also return values; let’s see this with some examples.

>>> secondList.index(4) # Acting like a function
>>> secondList.pop() # Acting lke a mutator
>>> secondList
[1, 2, 3, 4, 5]

As you can see, the first example we use the method index, this one works as a function, it takes a value as argument and returns the first index of the value in the sequence, index? Well an index is the position of an element in the sequence; this can vary from zero (0), remember this indexes start in zero, to the length of the sequence minus one.
In the second example, we use the pop method, this one works as a mutator, it returns the last element in the sequence and also removes it from the sequence, this makes List one of the ways to create task jobs to process things from a queue, but we will work on this later. I have talked about indexes right? So with indexes you can access a Python list whether is for assigning a value or getting it, using the square brackets you can access list.

>>> secondList[1]
>>> secondList[3] = 10
>>> secondList
[1, 2, 3, 10, 5]

We can also use negative indexes, the meaning of this is that you can get values from how many positions they are from the end, this is useful for getting the last value a so on.

>>> secondList[-1]
>>> secondList[-2]

If you try to access an element outside the boundaries, that is passing an index greater than the length minus one, you will get an index error such as this.

>>> secondList[5]
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
IndexError: list index out of range

You can also do with indexes a pretty cool thing that is called slicing, which is a way of creating a sublist within a list, cool right? So let’s create a new Python List using also the range function and slice it.

>>> thirdList = range(20)
>>> thirdList
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> thirdList[2:5]
[2, 3, 4]

In this example we create a List using the range function, this function is really useful when we want to create incrementing values, you can use range in several ways, if you provide two arguments instead of one, the first argument would be the first value of the resulting list, and the second argument the stopping value, keep in in mind when I say stopping value means, that this value is not included, a third argument can be included so you can get a list with every x values, for instance.

>>> range(2, 20, 2)
[2, 4, 6, 8, 10, 12, 14, 16, 18]

But getting back to slicing, we sliced the list by using the same square brackets, but this time we use a semicolon (:), which will separate the first index from the stopping index, again stopping means that the value in that index is not included in the resulting list, these places where the indexes supposed to be placed, they can be left empty and you will get the following outcomes.

>>> thirdList[:5]
[0, 1, 2, 3, 4]
>>> thirdList[5:]
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Empty indexes will generate based on which index in the slicing was empty, is the first one is empty, will generate a sublist from the beginning to the stopping index, and if the second one is empty, will generate a sublist from the first index to the end of the list. A third value can be provided in slicing to achieve the same result as the third argument in the range function.

>>> thirdList[2:10:2]
[2, 4, 6, 8]

Finally a pretty cool trick which can be implemented using slicing is to reverse a list.

>>> thirdList[::-1]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

One last thing we will cover on this entry is the use of Python built-in functions with list; they are kind of self-explain what they do, so take a look at the next examples.

>>> len(thirdList)
>>> max(thirdList)
>>> min(thirdList)
>>> sum(thirdList)

As you can see this entry covers the basics of Python Lists, but this is only the first part, in the second part we will cover the really cool stuff, list iteration, list comprehension, map, reduce, filter and lambda functions. I hope you have enjoy reading this as I enjoyed writing it, you can comment on the comments sections any doubt, question or suggestion, your opinion is very important to me, thanks.