Sunday, August 23, 2015

Python Basics - 016: Dictionaries

Previous chapter: Exception Handling



Python Basics - 016: Dictionaries and Sets

Let's see some complex data types

Dictionary

Dictionary is a data type which is a list of key-value pairs. It is very similar to Lists or arrays, instead of index values we will use some arbitrary value which can be any object like a number or a string.

Dictionaries can be initiated using the following syntax:


employeePosition = {
    "Alan": "Sr Developer",
    "John": "Quality Analyst",
    "Jack": "Delivery Manager"
}

Here the names are the keys and the positions are the values, there are many other ways to initiate a dictionary[1], but we'll stick to one syntax to make it more consistent.

Similar to a list or a tuple, dictionary's values can be accessed using the square bracket and passing the key value in the place of the index.


print("Alan is a", employeePosition["Alan"])

If we want to add a new employee to the mix, the syntax is very simple, just assign the value by using the key. If they key is not already available in the dictionary it will be added, if the key is present then it's value will be overwritten.


employeePosition["Julie"] = "Sales Professional"

Similar to object member variables, we can remove key-pairs from the dictionary using the del keyword[2]


del employeePosition["John"]

Let's check if he's really removed from the dictionary by looping over the dictionary:


for name, position in employeePosition.items():
    print(name, "is a", position);

The output will be:


Jack is a Delivery Manager
Julie is a Sales Professional
Alan is a Sr Developer

As we can see, John has been removed from the dictionary.

Unlike lists, dictionaries are easier to use when dealing with different kind of data, it is easier to access random values without iterating because the keys are distinct.

Dictionaries do not preserve any sort of order while storing your data, so while looping do not expect it to be in the order you inserted or any other order for that matter.

Sets and Frozensets

Sets are a list of objects that are distinct and hashable. Hashable objects are usually immutable built-in python data types, which means dictionaries and lists cannot be in a set. Objects which are instances of user defined classes can be used in a set as they are all hashable.

Sets also implement the operations available in mathematical set theory such as union, intersection, subset, superset, difference and symmetric difference.

While set is mutable, frozenset is immutable other than that they share all behaviour and functions.

Sets can be created using the {} syntax:


oscars = {"Jennifer", "Matthew", "Ellen", "Jack", "Leonardo", "Jack"}

As you can see Jack is repeated twice, but when you try to print the set, there will be only one instance of the name, set will automatically remove duplicates.


print("Stars at the oscars:",oscars);

output:


Stars at the oscars: {'Jack', 'Ellen', 'Matthew', 'Jennifer', 'Leonardo'}

We can also see that sets doesn't keep the order of elements according to the order of inserts of any other order, just like dictionaries.

To create an immutable set, we need to create a frozenset. Here's how:


afterparty = frozenset(["Jennifer", "Neil", "Woody", "Leonardo", "Rachel"])

Sets and frozen sets are easy to work with when having to check for presence or to do some set theory based operation. Here are some examples:


# to check if Jennifer went to the oscars

print("was Jennifer in the oscars?", "Jennifer" in oscars)

# to perform difference operation, to find who went to oscars but not the after party

print("Stars who came only to the oscars:", oscars - afterparty)

# to perform intersection operation i.e to find out who went to both oscars and the after party

print("Stars who attended both oscars and the after-party:", oscars & afterparty)

# to perform union operation, bring out all distinct values from both sets

print("All stars who were seen:", oscars | afterparty)

The output:


was Jennifer in the oscars? True
Stars who came only to the oscars: {'Jack', 'Ellen', 'Matthew'}
Stars who attended both oscars and the after-party: {'Jennifer', 'Leonardo'}
All stars who were seen: {'Jennifer', 'Rachel', 'Leonardo', 'Neil', 'Matthew', 'Ellen', 'Woody', 'Jack'}

Sets are a great way to group objects and to get distinct list of items.



We're actually at the end of the beginner's tutorial, I can't believe I've typed up so much stuff! This pretty much covers all the core functionality of python3 but this in itself is not sufficient for any real life projects.

Let's move on to a real life but a very tiny project. We will have to use libraries and modules such as url lib, sys, os etc., We will cover all of that as part of the next intermediate tutorial.

Let me come up with a project idea and I will post a comprehensive tutorial. Till then, happy coding!

I've posted all the code used in this tutorial in github

The tutorial content itself is available in bitbucket


References:

  1. https://docs.python.org/3.4/library/stdtypes.html#mapping-types-dict
  2. https://docs.python.org/3.4/tutorial/datastructures.html#the-del-statement
  3. http://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops-in-python
  4. https://docs.python.org/3.4/library/stdtypes.html#set-types-set-frozenset
  5. https://docs.python.org/3.4/tutorial/datastructures.html#sets



Previous chapter: Exception Handling

Python Basics 015: Exception Handling

Previous chapter: Classes and Objects Next Chapter: Dictionaries



Python Basics - 014: Exception Handling

This is somewhat an advanced chapter, it is very much relevant for beginners of python but have working knowledge of exceptions in other languages like Java.

Beginners to programming can revisit this chapter at your leisure!

Exceptions

Exceptions[1] are errors which happen in code even though everything is syntactically correct, errors which happen during runtime are called exceptions.

Most of the exceptions are due to environmental reasons, for example trying to access a file which is not available, trying to make a request to a server which is not reachable or simply the user has input some unexpected values to your program.

Let's see some examples:

Anything divided by 0 will result in infinity which is not understood by computers and is called a divide by zero exception:


a = 1/0

will result in


Traceback (most recent call last):
  File "/PycharmProjects/Tutorial/ExceptionHandling.py", line 1, in <module>
    a = 1/0
ZeroDivisionError: division by zero

Using a variable which is not defined. This may seem like a syntax or coding error, but remember from last chapter that we could add and removed variables at run time.


b = x * 10

will result in


Traceback (most recent call last):
  File "/PycharmProjects/Tutorial/ExceptionHandling.py", line 6, in <module>
    b = x * 10
NameError: name 'x' is not defined

Using incompatible types in a concat operation:


c = "String" + 42

will result in


Traceback (most recent call last):
  File "/PycharmProjects/Tutorial/ExceptionHandling.py", line 11, in <module>
    c = 'String' + 42
TypeError: Can't convert 'int' object to str implicitly

We can see that the exception is very informative about the problem the computer is facing, python tends to give us as much information as possible. We can see that python

  • shows the file name,
  • the line in which the error is happening,
  • the module/function name,
  • it quotes the line which causes the exception,
  • mentions the name of the built-in exception[2]
  • and the error message.

Exception Handling

Exception handling[3] is the way we handle errors occurring in the code at run time, we make provisions in the code to anticipate some errors and handle them properly instead of them crashing/exiting the application.

Like most other languages, Python also uses the try block concept: try-except

We'll simulate a scenario which causes a divide by zero error, in the following example assume the arguments of the function to be from user input. The program aims to print product and quotient of simple division when user supplies the values.


def printProductandQuotient(var1,var2):
    product = var1 * var2
    quotient = var1 / var2
    print("product of var1 and var2 is:", product)
    print("quotient when dividing",var1, "with", var2, "is:", quotient)

printProductandQuotient(10, 2)
printProductandQuotient(10, 0)

This is the implementation that we would normally do, but if you look at the second function call, we are passing 10, 0 because the user input them. We know that dividing 10 by 0 will result in an exception and the program will effectively exit.

The output will be:


product of var1 and var2 is: 20
quotient when dividing 10 with 2 is: 5.0
Traceback (most recent call last):
  File "/PycharmProjects/Tutorial/ExceptionHandling.py", line 15, in <module>
    printProductandQuotient(10, 0)
  File "/PycharmProjects/Tutorial/ExceptionHandling.py", line 10, in printProductandQuotient
    quotient = var1 / var2
ZeroDivisionError: division by zero

Now let me try and rewrite the same program to handle divide by zero exceptions and print another message instead of crashing.


def printProductandQuotientProper(var1,var2):
    product = var1 * var2
    print("product of var1 and var2 is:", product)
    try:
        quotient = var1 / var2
        print("quotient when dividing", var1, "with", var2, "is:", quotient)
    except ZeroDivisionError:
        print("we cannot divide a number by 0, it results in infinity")

printProductandQuotientProper(10, 2)
printProductandQuotientProper(10, 0)

Now we are doing the division inside a try block, any ZeroDivisionError that occurs will be caught by the except and we'll print the custom message. Now the output is available and we haven't crashed the application!


product of var1 and var2 is: 20
quotient when dividing 10 with 2 is: 5.0
product of var1 and var2 is: 0
we cannot divide a number by 0, it results in infinity

We can use multiple except: blocks for a single try: incase there is a possibility of other exceptions occurring.

You can also define custom exception classes[4] for complicated cases, however it is not the time to go into that, I've never used custom exceptions in java in all my years of coding, it is just overkill.

Finally()

In try-except block there is another element that does cleanup work[5]. It is another block which is executed irrespective of exceptions. If code enters into the try block, the finally block will definitely be executed.

It lets us do some last minute cleanups in case there is an application crash or smoother exception which we have not mentioned in the except: block.


def testFinally():
    try:
        x = 1/0
    except TypeError:
        print("there was a type error in the code")
    finally:
        print("some other exception occurred, gracefully shutting down")
        ''' do something here to gracefully shutdown app'''

testFinally()

Here's a sample code, in it we are not catching the proper exception, so the application will still crash even if we have the try block, but while exiting the finally block is also executed.

So the output will be:


Traceback (most recent call last):
  File "/PycharmProjects/Tutorial/ExceptionHandling.py", line 39, in <module>
    testFinally()
  File "/PycharmProjects/Tutorial/ExceptionHandling.py", line 32, in testFinally
    x = 1/0
ZeroDivisionError: division by zero
some other exception occurred, gracefully shutting down

Exceptions as we've seen are essential for a crash-free program. Let's move on the next chapter: Dictionaries


P.S: all the code used in this tutorial is available in github


References

  1. https://docs.python.org/3.4/tutorial/errors.html#exceptions
  2. https://docs.python.org/3.4/library/exceptions.html#bltin-exceptions
  3. https://docs.python.org/3.4/tutorial/errors.html#handling-exceptions
  4. https://docs.python.org/3.4/tutorial/errors.html#user-defined-exceptions
  5. https://docs.python.org/3.4/tutorial/errors.html#defining-clean-up-actions



Previous chapter: Classes and Objects Next Chapter: Dictionaries

Python Basics - 014: Classes and Objects

Previous chapter: Scope of Variables Next Chapter: Exception Handling



Python Basics - 014: Classes and Objects

Object oriented programming is something that I identify mostly with java as it is the only other language that I know. Let's see how python handles classes and objects.

Classes are like blueprints for creating objects, classes usually contain a combination of variables and functions.

If you take fish as an object, then the fish may have descriptors about it such as size, weight, color, species, etc. these are analogous to member variables of an object. The fish may also have functions like swim, eat, breathe, etc, these are analogous to member functions.

Let's get started with the syntax for defining classes


class Fish:
    size = "large"
    color = "white"

    def swim(self):
        print("the", self.size, self.color, "fish is swimming")


goldfish = Fish()
goldfish.swim()
goldfish.size = "small"
goldfish.color = "gold"
goldfish.swim()

you should get the below output


the large white fish is swimming
the small gold fish is swimming

What we can see from the example is that

  • we can define class using the class keyword.
  • all member methods take by default the self argument which passes in the object in which the method is in, so as to access the variables (remember variable's scope?)
  • member variables have a default value, hence it works without us passing any values to them.
  • member variables of an object can be accessed by using the . dot operator, same goes for member functions.

We can also initiate a object with some values during the creation of the object, similar to a constructor in java. we use __init__() function in python. In fact calling Fish() will internally call Fish.__init__() automatically if the function is implemented.

Here's the above example, slightly modified:


class MarineCreatures:
    size = "large"  #class variable
    def __init__(self, color):
        self.color = color  #instance variable

    def swim(self):
        print("A", self.size, self.color, "marine creature is swimming")

seahorse = MarineCreatures("blue")
seahorse.swim()

output:


A large blue marine creature is swimming

Here the instance variable is initiate when the class is created, however unlike class variables, instance variables are not optional. If you create the object with the following syntax, it will throw an error because the argument number is not matching for the __init__() function.

Some things to note about objects in python:

  • Unlike java, member variables are by default public, and there is no private variables in python.[3]
  • We can remove writable member variables at runtime.[4]
  • We can add member variables at runtime [6]
  • We can define functions inside other functions, although it is not good practice to use it that way[5]

Classes are quite important to how we code in python, even though it is not necessary, I'd like to use object oriented approach to make the project more modular and easily readable.

There are other concepts about classes like inheritance, but we'll see to them later. Next stop is Exception Handling


P.S: all the code used in this tutorial is available in github


References:

  1. https://docs.python.org/3/tutorial/classes.html#a-first-look-at-classes
  2. https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables
  3. https://docs.python.org/3/tutorial/classes.html#private-variables
  4. https://docs.python.org/3/tutorial/classes.html#instance-objects
  5. https://docs.python.org/3/tutorial/classes.html#scopes-and-namespaces-example
  6. https://docs.python.org/3/tutorial/classes.html#odds-and-ends



Previous chapter: Scope of Variables Next Chapter: Exception Handling

Saturday, August 22, 2015

Python Basics - 013: Scope of variables: Global and local

Previous chapter: Dynamic Arguments in functions Next Chapter: Classes and Objects



Python Basics - 013: Scope of variables: Global and local


As we know variables are identifiers for data, they hold different types of data and let us access them whenever we want. There are a set of rules to use variables in different locations or context, this becomes important specially when dealing with functions.

Scope is defined as the place where the variable is accessible.

Global Variables

Variables which can be accessed anywhere in the program are called global variables.

Consider the below example:


num1 = 10

def addToNum(num2):
    print(num1+num2)

addToNum(12)

Here num1 is a variable which is outside the function, but is not a global variable. num1 can be accessed inside the function but cannot be modified. If you tried to do something like below, it would through an error.


num1 = 10

def addToNum(num2):
    num1 += 20
    print(num1+num2)

addToNum(12)

We'll get UnboundLocalError: local variable 'num1' referenced before assignment, because the num1 variable is accessible but not mutable hence the error is thrown.

The error will go away if we make num1 a global variable.

Here's how to do it.


num1 = 10

def addToNum(num2):
    global num1
    num1 += 20
    print(num1+num2)

addToNum(12)
print("num1: ", num1)

Using the global keyword we can convert the num1 into a global variable which can be modified inside the function, the changes made by the function persists outside the scope of the function too as can be seen from the output below:


42
num1:  30

Usually the global variables are not recommended by various teachers and companies because it is difficult to track changes and object oriented designs prohibit this kind of behaviour but it's nice to know how it works in normal cases.

Usually passing arguments and getting the values using return statements is the way to go.

We'll try to do the functionality using a return statement:


def addToNumber(num2):
    gnum1 = num1
    print(gnum1+num2)
    return gnum1

x = addToNumber(12)
print("num1: ", x)

We'll get the same output.


42
num1:  30

Local Variables

Local variables on the other hand exist only in the scope of the function in which they are defined. In the above example gnum1 is a local variable and it can only be used inside the addToNumber function, anywhere else in the program gnum1 doesn't exist.

We can reuse the variable name but it is generally a bad practice to do so as it might be confusing.

There's nothing much to it. Let's move on to Classes, Objects and object oriented programming.


P.S: all the code used in this tutorial is available in github




Previous chapter: Dynamic Arguments in functions Next Chapter: Classes and Objects

Friday, August 21, 2015

Python Basics - 012 Dynamic Argument Count

Previous chapter: Intro to Functions Next Chapter: Classes and Objects



Python Basics - 012: Dynamic Argument Count


Functions in python take a variable number of arguments if specified using the * operator, let's look at an example:


def hellotoMany(name1, *others):
    print("Hello", name1)
    for eachname in others:
        print("hello ", eachname)

hellotoMany("Alan", "Jack", "Arya", "Jon")

As we can see in the example above a * before an argument name will give let you give however many arguments to the functions and that will act as a tuple of objects inside the function.

Hence output of that will be:


Hello Alan
hello  Jack
hello  Arya
hello  Jon

The same can be done with keyword arguments, if you remember from last chapter, keyword arguments have the name of the arguments along with their values while calling them. So dynamic keyword arguments can be defined using ** operator. Here's an example of that:


def hellotoManyMore(name1, **kwargs):
    print("Hello", name1)
    print("Hello", kwargs.get('name2'))
    print("Hello", kwargs.get('name3'))

hellotoManyMore("Alan", name3="Jack", name2="Jon")

The output will be as expected,


Hello Alan
Hello Jon
Hello Jack

This will let us retain or mess with the order of arguments when calling the function.

The convention is usually *args and **kwargs, but you can use whatever meets your fancy.

Here's a more thought out example snippet:


def doSomething(first, second, third, **kwargs):
    if kwargs.get("action") == "sum":
        print("The sum is: %d" % (first + second + third))

    if kwargs.get("number") == "second":
        return second

result = doSomething(1, 2, 3, number="second")
print("1. Result: %d" % result)
result = doSomething(1, 2, 3, action="sum", number="second")
print("2. Result: %d" % result)

The above program tries to print a sum if the action parameter is passed and return the second element. If the action argument is not passed then the if condition regarding the action statement is false and the subsequent print() is not executed. Hence the output of the above snippet is:


1. Result: 2
The sum is: 6
2. Result: 2

We can see the optional parameters are indeed optional and even if we use them inside the function it is not throwing an error.

Let's learn about the variables and how they behave in different scopes in the next chapter.


P.S: all the code used in this tutorial is available in github


References:

  1. http://www.learnpython.org/en/Multiple_Function_Arguments
  2. https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists
  3. https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments



Previous chapter: Intro to Functions Next Chapter: Classes and Objects

Wednesday, August 5, 2015

Python Basics - 003.5 - Data Types in Python 3

Previous chapter: Hello World! Next Chapter: IDEs



Data Types in Python 3


I just realised that we're putting off an important discussion: data types. This determines what types of variables we'll have and how data interacts with each other inside python.

Now usually basic data is grouped into Numbers, Text, Truth value (Boolean) and Lists/Collections.

I'm listing the official python names for the data types which are supported by python core. All data types will be stored as objects unlike C or Java, there are no primitive data types.

  • Boolean - represented by True or False
  • Numbers (int, float and complex) - integers and decimal numbers
  • Strings (str) - Sequence of unicode characters in python 3, behaviour changes for 2.x
  • Bytes (bytes, byte array) - Raw binary data, like images.
  • Lists & Tuples (list, tuple and range) - list of other data types, full chapter is written for it.
  • Sets (set) - list of distinct values, see specific chapter for more
  • Dictionaries (dict) - list of key:value pairs; where keys in a dict should be distinct and made of numbers or strings and not lists or sets

Boolean:

The truth of any statement can be verified into True or False, these are constants in Python which can be used where needed. Booleans also result in any comparison or any other expressions. Booleans are constructed as a subtype of integer and True is 1 and False is 0.


>>>print(3>4)
False
>>>print(5>4)
True


Numbers:

int is an integral number with no decimal point. Python 3 doesn't differentiate integers into many data types based on size, there are no long and int. Just int and int is limitless.

float is a real number with a decimal point, the precision and limit of float is device based and the information can be obtained using sys.float_info.


>>> myInt = 21
>>> myInt
21
>>> myFloat = 2.1
>>> myFloat
2.1

Complex numbers are numbers which have both real and imaginary components, You can go here & here for explanation on what is real and what is imaginary but I don't think we'll ever encounter complex arithmetic in any real scenario. In any case, read about complex numbers when you have ton of time to burn. When you're sufficiently confused, let's take a break and move on to Strings.

Strings:

Strings are immutable array of unicode characters. They can be enclosed using single or double quotes.


firstName = "Alan"
lastName = 'Francis'

You can access specific characters by using


>>>firstName[3]
n

You can concat strings using the + operator


>> firstName+' '+lastName
Alan Francis

We'll see Bytes, Lists, Sets and Dictionaries later on in their own chapters.


References:

  1. https://docs.python.org/3.4/library/stdtypes.html#built-in-types
  2. https://docs.python.org/3.4/library/stdtypes.html#boolean-values
  3. https://docs.python.org/3.4/library/stdtypes.html#numeric-types-int-float-complex
  4. https://docs.python.org/3.4/library/stdtypes.html#text-sequence-type-str
  5. https://docs.python.org/3.4/library/stdtypes.html#binary-sequence-types-bytes-bytearray-memoryview
  6. https://docs.python.org/3.4/library/stdtypes.html#sequence-types-list-tuple-range
  7. https://docs.python.org/3.4/library/stdtypes.html#set-types-set-frozenset
  8. https://docs.python.org/3.4/library/stdtypes.html#mapping-types-dict
  9. https://en.wikipedia.org/wiki/Complex_number
  10. https://en.wikiversity.org/wiki/Complex_Numbers
  11. http://www.diveintopython3.net/strings.html
  12. https://en.wikibooks.org/wiki/Python_Programming/Data_Types
  13. http://www.w3resource.com/python/python-data-type.php



Previous chapter: Hello World! Next Chapter: IDEs

Sunday, August 2, 2015

Python Basics - 011: Functions

Previous chapter: Lists and Tuples Next Chapter: Dynamic argument count



Defining Functions

Python functions are equivalent to Java Methods or C functions. If you look at documentation sometimes functions will be called as methods, It is because functions of an object are called methods conforming to Object oriented standards. Functions are defined before they are called in the code unlike in Java, because Python is interpreted and not compiled in advance. So python executes as soon as it gets the python file from top to bottom and throws an error when it encounters one. On the other hand Java wouldn't even consider executing a file with errors as error checks are done in compile time.

Syntax for creating a function is to use the def keyword. See example below to see a function in action


def printHi():
    print("Hi!")

printHi()

output:


Hi!

So whenever you want to say hi in the program you can call this function instead of using print() function. Although it doesn't make sense to use a function for a small task, more and more complex tasks need to be broken down into modules and each performing an operation which is delegated to a function. This just makes it easy to unit test the program and to make sure where the error is.

Functions can also accept parameters and return an object. While the number of parameters are limitless, there can be only one return value.


def printHiName(name):  # parameterized function, how about we say Hi using a name.
    print("Hi", name)

printHiName("Alan")

output of this will be


Hi Alan

Let's see another example for parameterised function with a return value


def add(var1, var2):  # function with a return value, how about adding 2 values?
    return var1+var2

print("Add 2 and 5: ", add(2, 5))

output of this will be


Add 2 and 5: 7

The same function can be called by using the name of the parameters to decrease confusion. This way of using the name of the parameter is called keyword argument:


add(var1=2, var2=5)

This will not make a difference in this method but using a large number of parameters you may get confused about what the parameters represent, this will increase readability and will enable us to change the order of the parameters like the example below:


add(var2=5, var1=2)

Default arguments while defining functions

Default arguments[2] are how we implement optional parameters for python functions. Optional or default arguments or parameters which have a default value if you don't use them.

See the example below:


def printHello(name="Stranger"):
    print("Hello ", name)

printHello("Alan")

printHello()

Here in the above example, both calls of printHello() are valid and when name is not passed, it defaults to "Stranger"

So the output will be:


Hello  Alan
Hello  Stranger

There is another way to implement multiple arguments for a function in Python, We'll see more about it in the next chapter.


P.S: all the code used in this tutorial is available in github


Reference:

  1. https://docs.python.org/3.4/tutorial/controlflow.html#defining-functions
  2. https://docs.python.org/3.4/tutorial/controlflow.html#default-argument-values



Previous chapter: Lists and Tuples Next Chapter: Dynamic argument count

Python Basics - 010 - Lists and Tuples

Previous chapter: Operators in Python 3 Next Chapter: Functions



Lists and Tuples

Lets get one thing out of the way, Lists and Tuples are basically the same. Tuple is constant and immutable so the size or number elements in a tuple cannot be changed/increased.

A List is mutable, you can add or remove elements from the lists. Tuple is rarely used because it cannot be changed, but it is faster to create and iterate than a Python list.

using comma separated values enclosed with normal braces or without any braces will create a tuple, same values with square bracket will create a List. Lists are more similar to Arrays in Java than to LinkedLists.

See examples below, the index to access the elements start from 0, which is familiar to any programmer from c or java.


# ways to initiate a tuple
tupleExample = 5, 6, 2, 6
tupleExample1 = (5, 6, 7, 8)

print("Tuple ", tupleExample)
# accessing a tuple's element
print("Second element of tupleExample ", tupleExample[1])

# ways to create a list, use square brackets
listExample = [5, 2, 4, 1]

print("List:", listExample)
# accessing a List's element
print("Third element of list:", listExample[2])

Output will be:


Tuple   (5, 6, 2, 6)
Second element of tupleExample  6
List: [5, 2, 4, 1]
Third element of list: 4

Now that we've establishing that tuples are only static lists and we cannot modify it. Lists, however can be modified, Let's get to know how to modify a list and what all operations we can do.

We can get a part of the data out of the list by a process called slicing, we can slice a list by passing a range as a index value


# slicing of data is to get a subset of the list as another list, by providing a range for the index
print("a slice of the data:", listExample[1:4]) # brings up 1, 2 and 3rd element

We can get the elements from the last by using negative index values, see the example below to see how


# The last index value is -1 and the last but one is -2 so on and so forth
print("The last element in this list:", listExample[-1])

output:


The last element in this list: 1

We can use append to add a value to the end of a list. Here's an example:


listExample = [5, 2, 4, 1]
print("List:", listExample)
listExample.append(2)
print("2 added to the end of the List:", listExample)

output:


List: [5, 2, 4, 1]
2 added to the end of the List: [5, 2, 4, 1, 2]

As expected the value 2 is added to the end of the list, same can be done for a list of Strings or decimal values the same way it is done for integers.

What if we wanted to add an element at a specific position in the list, we could do that using the insert function of the list. Adding to the above example, here's a way of adding a value 77 at the third position


listExample.insert(2, 77)
print("77 inserted at 3rd location in the List:", listExample)

Let's see if the output reflects what we've tried to do and we can see below that we've got the result we wanted.


List: [5, 2, 4, 1, 2]
77 inserted at 3rd location in the List: [5, 2, 77, 4, 1, 2]

What if we added the 2 previously by mistake and wanna take it out of the list, we can use the remove function. remove function will remove the first occurring value as passed to the function. To remove a element based on position, we have to pass the list with the index as a parameter. Let's see the examples below to be more clear.


listExample.remove(2)  # will remove the first occurring 2 in the list
print("value 2 is removed from the list:", listExample)

listExample.remove(listExample[1])  # will remove the 2nd element of the list
print("2nd element removed from list:", listExample)

From the output below, we can see the expected behaviour


value 2 is removed from the list: [5, 77, 4, 1, 2]
2nd element removed from list: [5, 4, 1, 2]

The index can also be used in a different way to count from the last value, by passing a negative value to the index. Similar to how we access it.

To find the index of an element whose position is unknown, we can use the index function of the list object:


print("location of 5 in the list:", listExample.index(5))

To find out the number of occurrences of a particular value in a list, use the count() function of the list object.


print("no of times 2 occurs in the list:", listExample.count(2))

To sort the list, use the sort function. The sort function works for string lists as well where is sorts in alphabetical order.


listExample.sort()
print("Sorted List:", listExample)

output:


Sorted List: [1, 2, 4, 5]

Here's the complete example program for this chapter,


# ways to initiate a tuple
tupleExample = 5, 6, 2, 6
tupleExample1 = (5, 6, 7, 8)

print("Tuple  ", tupleExample)
# accessing a tuple's element
print("Second element of tupleExample ", tupleExample[1])

# ways to create a list, use square brackets
listExample = [5, 2, 4, 1]

print("List:", listExample)
# accessing a List's element
print("Third element of list:", listExample[2])

# slicing of data is to get a subset of the list as another list, by providing a range for the index
print("a slice of the data:", listExample[1:4])  # brings up 1, 2 and 3rd element

# we can access the list from the end, using negative index values.
# The last index value is -1 and the last but one is -2 so on and so forth
print("The last element in this list:", listExample[-1])
print("The last but second element in this list:", listExample[-2])


listExample = [5, 2, 4, 1]
print("List:", listExample)
listExample.append(2)
print("2 added to the end of the List:", listExample)

listExample.insert(2, 77)
print("77 inserted at 3rd location in the List:", listExample)

listExample.remove(2)  # will remove the first occurring 2 in the list
print("value 2 is removed from the list:", listExample)

listExample.remove(listExample[1])  # will remove the 2nd element of the list
print("2nd element removed from list:", listExample)

# to find the index value of the element 5, it gives the first matching values's index
print("location of 5 in the list:", listExample.index(5))

# to find out the number of occurrences of a particular value
print("no of times 2 occurs in the list:", listExample.count(2))

# To sort the list, use the sort function
listExample.sort()
print("Sorted List:", listExample)

For verification, here's the output of the program


Tuple   (5, 6, 2, 6)
Second element of tupleExample  6
List: [5, 2, 4, 1]
Third element of list: 4
a slice of the data: [2, 4, 1]
The last element in this list: 1
The last but second element in this list: 4
List: [5, 2, 4, 1]
2 added to the end of the List: [5, 2, 4, 1, 2]
77 inserted at 3rd location in the List: [5, 2, 77, 4, 1, 2]
value 2 is removed from the list: [5, 77, 4, 1, 2]
2nd element removed from list: [5, 4, 1, 2]
location of 5 in the list: 0
no of times 2 occurs in the list: 1
Sorted List: [1, 2, 4, 5]

Lists are very important to any programming language, just as important as string manipulations. Let's move on to another integral part of any programming language: functions.


P.S: all the code used in this tutorial is available in github


References:

  1. https://docs.python.org/3.4/tutorial/introduction.html#lists



Previous chapter: Operators in Python 3 Next Chapter: Functions