How to update a list in Python 2.7

Python lists help the coder to store information for later usage in their software development projects. As you may know, one can easily declare a list object in Python computer programming language by using the syntax which is being shown below.

list_object = []

Based on my personal experience with Python computer programming language, a list can have different type of elements in it. To make things more practical, I am writing the following list.

list_object = [1, 2, 3, ‘coder’]

Being mutable objects, Python lists can change in time. What does it mean? It means that once you have declared a list, you can easily update its elements by using the builtin operations supported by the list object.

The following syntax can be used in Python code to append a new element in a list.

[].append(element)

If one tries to run the above code, their Python interactive shell will throw an error, because the element has not been declared. The example shown above stands only for explaining the append operation, which is specific to list objects in Python computer programming language.

Now, let’s get our hands dirty. Having declared a real list in our Python interactive shell, we can easily update it, by using the append operation; like shown below.

list_object.append(4)

Once the list is updated successfully, we can easily check its new element like shown below.

list_object

The following will get printed on your Python console.

[1, 2, 3, ‘coder’, 4]

Not only do list objects support population with new elements, but they also support depopulation too. The syntax for removing an element from a list is being shown below.

[].pop(index_of_element_to_be_removed)

Let’s try to remove from the list, the element we just added by using the pop operation like shown in the following example.

list_object.pop(4)

If the above piece of Python code is being executed successfully in your Python interpreter shell, you will get the following output on the console.

4

In our example, the index of the element we removed, is the same as the value of the element.

To remove another element from the list_object, use the pop method of the Python list, by providing as an argument the index of the element you want to remove.

Let’s try to remove the element ‘coder’ from the list_object.

list_object.pop(3)

If the above piece of Python code is being executed successfully in your Python interactive shell, you will get the following output.

‘coder’

And now, if we check the list named list_object, we will realize that it has been updated.

list_object

Once the above code is being run, the following comes in the Python console.

[1, 2, 3]

Final thoughts

There is another way which I do know that can be used to update list objects in Python, but I am going to share that in another article, in which I am going to explain Python lists in details for complete beginners. Specific Python list methods such as append and pop, are enough to add new elements to the list, and remove existing elements from the list.

How to use the def statement in Python to create a function

Functions play a very important role in computer programming, especially when it comes to grouping code statements together with the main purpose of creating specific utilities to solve certain problems. Being a feature rich computer programming language, Python comes with the tools which one can easily use to write functions to automate their daily tasks.

The following syntax is being used to create a function in the Python computer programming language.

def find_sum():pass

A function in Python is composed of nested statements. It acts like a package of the statements so it can group them together to solve a specific problem. For a function in Python computer programming language to properly work, it must return something back to the caller.

A coder can use the Python return statement inside a function to return something to the caller. The syntax for it is being shown below.

def find_sum():return 1

If executed, the above function will return the value of 1 back to the caller. To make things more practical, let’s fire up the Python interactive shell and run the code being shown above.

find_sum()

After running the above, in my Python interpreter shell, the following value was returned.

1

As a Python coder, you can use the def statement to write your own custom functions. The above one, does not do anything special at the moment, it just returns a value.

A real world function in Python computer programming language, should make use of arguments. The syntax for it is being shown below.

def find_sum(a, b):return a + b

The above function takes two arguments, a and b. Then it calculates and returns their sum. To run the above function, you have to provide two numbers like shown below.

find_sum(5, 3)

Once it is being run, the above code returns the following result.

8

Final thoughts

To code in a computer programming language, means to solve specific problems. Python functions play a very important role in software development. One can easily create their own custom functions by using the def statement like explained earlier in this article.

How to check if a specific path exists or not by using Python

Each file or folder in the filesystem has a path, a specific one. Python coders deal a lot with paths of files in their computer programming projects, especially when developing software that deals with the utilities of the operating system. Being rich in already builtin features, Python offers many utilities that can help the coder accomplish the tasks they want, without any pain.

One can easily use the os module offered by Python to check if a specific path exists on their operating system or not. The following syntax, shows the usage of the os.path.exists utility.

os.path.exists(path_in_here)

When the os.path.exists Python statement is executed, it returns True or False, depending on the existence of the path which is being checked. It’s usage is very easy, but before one can do that, they have to import the os module first, like shown below.

import os

Once the Python os module is imported, one can easily utilize its resources. Since the purpose of this tutorial is to teach one how to check for the existence of the path of a file in their operating system, I am giving the following practical example to illustrate it.

import os
os.path.exists(‘test’)

When the above statements are executed in the interactive Python shell, False is being returned.

False

Why? Because the path which we are looking for does not exist in the system. With the main purpose of illustrating the usage of the os.path.exists utility when a path exists, I am running the example shown below on my unix based machine.

os.path.exists(‘/usr/local/bin/python’)

When the above Python statement is executed on the Python interactive shell, on my computer, the True value is being returned.

True

This time the True value is being returned, because the path which I am checking for, exists in the operating system.

Final thoughts

Python comes with the builtin tools that can help the coder solve almost any kind of problem. By using the os.path.exists utility, one can check for the existence of a path in their operating system.

How to find the length of an object in Python

Python is a high level computer programming language which comes with many already builtin tools that help the coder to accomplish almost any task, they need to. Being an object oriented computer programming language, some of the Python objects have a length, which can be easily accessed with the help of the Python builtin utility called len().

Python objects that have a length are strings, tuples, lists and dictionaries. One can easily use the Python builtin function len() to find the length of an object which supports one.

According to the official Python documentation, the Python builtin function len(), stands for the length of an object in Python computer programming language. As I have mentioned in earlier tutorials related to Python, the Python computer programming language is easy to read, like a human language.

The following is the syntax which can be used to utilize the Python builtin function len(), with the main purpose of finding the length of an object.

len(Python object which supports length in here)

With the main purpose of illustrating the usage of the Python builtin len() utility in a practical example, I am creating the following string.

website = ‘codetheory.in’

To find the length of the above Python string, the Python builtin len() utility can be easily utilized like shown below.

len(website)

When the above piece of code is being run in the Python shell, in interactive mode, the following is being displayed on the console. It is the number of the characters found in the string ‘codetheory.in’.

13

As mentioned earlier in this article, Python objects such as tuples, lists, and dictionaries have a length too. To give other practical examples of the Python len() utility in action, I am building the following objects.

t = (1, 2, 3)
l = [1, 2, 3, 4, 5]
d = {‘profession’: ‘coder’}

In the above Python code, there are three objects being declared: a tuple, a list and a dictionary. One can easily find the length of each one of the above Python objects by using the builtin len() utility in Python computer programming language; like shown below.

length_of_tuple = len(t)
length_of_list = len(l)
length_of_dictionary = len(d)

To print the length of each of the Python objects declared about, make use of the Python print statement like shown below.

print(length_of_tuple)
print(length_of_list)
print(length_of_dictionary)

Final thoughts

The Python computer programming language comes with many already builtin tools which can ease the work of the coder and speed up the process of development. One of them is the len() function, which can be used to find the length of a Python object which supports one.

Functions in Python, explained in details for complete beginners

One who has mastered the basic Python utilities such as variables, numbers, lists, tuples and dictionaries; should start to learn about functions and their usage, unless they want to remain in the beginner stage and stop progressing with their journey as a Python coder.

Based on my personal experience with the Python programming language so far, a function is the tool which groups a set of code statements together with the main purpose of helping the coder to utilize the same resources more than one in their applications, without repeating themselves.

By using functions not only do Python coders reduce their future work, but they also group code instructions together with the main purpose of developing a specific utility which solves a specific problem. For example, the following function written in Python computer programming language, is specifically developed to find the sum of two numbers and return the result back to the user.

def find_sum(a, b): return a + b

The above Python function takes as input two parameters,a and b. Based on the value of the parameters, it finds their sum and returns it to the user. As you may know, Python supports arithmetic operations by default.

a + b # python arithmetic operation

Why use functions in Python

There are many reasons why Python coders make use of function in their computer programming projects, but the following is the main two.

  • To maximize code reuse
  • To minimize code redundancy

Another obvious reason why those who code computer software make use of functions, is to split their project into small components which make the process of application development really easy and simple to track the code statements under the hood.

Since Python is an object oriented computer programming language, it is always a good idea to bring practical examples with the main purpose of making the theory completely easy to understand for everyone, even to those who have no coding experience at all.

Imagine if someone gave you a project which deals with the wrapping of the ffmpeg multimedia framework. Wouldn’t it make sense to write specific functions for extracting audio, cutting the videos, extracting images?

Based on my personal experience with Python computer programming language, it would make totally sense to split the project into simple components, by using specific functions. The following is a simple architecture I am writing to demonstrate how Python functions help in splitting the project into small utilities.

ffmpeg.extract_audio
ffmpeg.cut_video
ffmpeg.extract_images

In the above block of Python code, the ffmpeg is the module, and the others is the functions; the small components which build the functionalities of the project.

How to declare a function in Python

Python coders declare functions by using the def statement, which means to define a new function. The example shown below, is a practical one.

def new_function():pass

The pass statement is being used to skip the further coding of the function, it can be used in class statements too like shown below.

class A:pass

One can easily write a new function in Python by using the def statement. For a Python function to properly work, it must return something, a value. The Python return statement is being used to exit the function and send back the value to its caller.

def find_sum(a, b, c):return a + b + c

Once a function is being declared with the help of the def statement, a new object is created and assigned to the name of the function. According to the official Python documentation, the function does not exist until the moment the interpreter reaches and runs the def statement where the function is defined.

A Python function can be assigned to a variable, stored in a list and even nested in if statements or while conditional loops.

For example, the following example illustrates how a function can be nested inside a Python if statement.

if execute:find_sum(1, 2, 3)

Time to open the Python interpreter and put some theory about functions in practice. Once you have launched the Python shell, make sure to write the following function.

def display_name(name):pass

The above function does not do anything at the moment, since we just declared it and passed with the Python pass statement.

Try to extend the above function like shown below.

def display_name(name):print(name)

Our function is not ready to be put in work. Although a very simple one, it is good enough to materialize the theory and the concepts we have covered so far.

The Python function display_name takes an input and displays it on the screen, by making use of the builtin function called print.

Run the following and see what happens.

display_name(‘codetheory’)

One can easily assign a function to a variable, and do the call from the variable. A practical example to illustrate such theory is being shown below.

f = display_name
f(‘codetheory’)

The above function does not return anything, it just displays stuff on the console with the help of the builtin Python print statement.

A function can also have arbitrary user-defined attributes, with the main purpose of recording data which can be used later. Take the following example, a simple function which calculates the final price of a product based on the tax.

def calc_price_of_product(price):
tax = 30
final_price = tax + price
return final_price

How to call a function in Python

Once a function is declared, for it to work, it must be called. One can easily call a function in Python by using the following syntax.

my_function()

Notice the brackets in the above call. Based on the declaration of the function, one needs to pass the right number of arguments as an input, before calling it; otherwise they will run into errors thrown by the Python interpreter.

A call of the Python function display_name needs to be done with an argument as an input. Try to call the Python function display_name like shown below and see for yourself what happens in the interactive interpreter.

display_name()

The interpreter will throw the following error, telling the user that they need to run the function with exactly one argument.

Traceback (most recent call last):
File “”, line 1, in
TypeError: display_name() takes exactly 1 argument (0 given)

Final thoughts

Functions make it very easy for the Python developer to write their projects without repeating themselves. Another reason why Python functions make a great utility when it comes to software development, is the fact that they help to split a big project into small components, specific to carry out certain tasks.

Through this article, we went through basic concepts of Python functions, knowledge which everyone should master in order to progress on their journey as Python coders, especially the complete beginners.

Complete list of skills you need to become a Webmaster, first part

Being a computer nerd who has experimented with a lot of different things, I have had the opportunity to build websites for people, completely from scratch. Not only have I developed websites, but I have also managed them since they’re dynamic web applications which require updates. This job, which I am currently doing right now, is called Webmastering.

In other words, Webmastering is the process of maintaining one or many websites. Personally I do love such skill, as not only it is widely applied in the computer world, but it also helps one interact with different people, from different regions and cultural backgrounds.

Although a junior Webmaster, the passion I have for the craft gives me confidence to guide others, especially newbies who have no idea about the field. Having earned some experience in the Webmastering field, I am going to compile a list of skills one needs to master in order for them to start managing websites on internet, for their personal usage, or for profit.

Html skills

Web applications make use of the html technology, a computer language which is used to structure information on the web applications. Easy to read and write, html is being widely used by Webmasters worldwide during their daily activities while managing websites on the internet.

Based on my personal experience with the Webmastering, html is for sure a necessity, especially if one wants to develop their web applications completely from scratch. Most of the websites a Webmaster manages, are not static, they may break and stop working; that’s why it is always a good idea to get html skills on your toolset.

There are plenty of resources on the internet from which one can learn html, completely for free. Although html is not hard to learn, it may be a bit tricky to practice, since the beginner has no idea how to put it in use in real projects.

With the main purpose of helping beginners and intermediate geeks to effectively utilize the html technology in real projects, I am going to share many tutorials in codetheory.in. For now, just make sure you have written it on your notes, how important it is for one who wants to become a Webmaster, to learn and master the Hypertext Markup Language.

A server side language

Most of the web applications is based on three tiers, such as the rendering tier, the logic tier and the storage tier. Html is a good technology when it comes to rendering, since it is being executed in the browser. It does not make sense to use html as a scripting language which handles logic, for example trying to communicate with the database of a web application. It can not do such thing as it is not being built for that!

There are many computer programming technologies one can use to handle the logic of a web application. Nowadays computer nerds develop programming languages to solve specific problems, and there is many technologies one can pick up when it comes to implementing the logic tier of their web application.

Personally I prefer Python. Not only it is open source, free as in beer and truly effective when it comes to prototyping, but there is also so many web frameworks written in it which make the life of a Webmaster truly easy. Easy to read and write, Python is a very good tool a true Webmaster should learn.

Most of the Webmasters out there make use of PHP, which is great when it comes to scripting stuff and writing web applications too, but there is no way its syntax can beat Python. Personally I don’t know PHP, and right now I have no plans to learn it. For sure PHP is a very useful tool to the Webmaster since there is many web applications written in it on the Internet, but I do prefer Python.

There is many scripting languages you can choose from when it comes to accomplishing your tasks as a Webmaster, choose the one that fits your needs the best.

A database technology

Most of the web applications programmers write nowadays are database driven as they need to store information somewhere, such as name, address, phone number, credit card etc. There is so many technologies that can be used as a database for web applications. A Webmaster should know basics of the technology they’re using in their storage tier, so they can easily fix almost any problems that come out of it.

Database technologies such as MySQL, PostgreSQL and MongoDB are currently being used widely by almost any Webmaster who truly knows what he or she is doing.

Although I am not a master of SQL databases, I totally recommend to you MySQL as it has a long history in the computer programming industry.

Final thoughts

One does not master their craft over night. Webmastering can not be mastered in one day, nor in one month, nor in one year. A good Webmaster should learn about the main technologies being used to develop the basic structure of a web application before diving deep into the waters. The three skills that one should learn in order to start their journey as a Webmaster shared in here, is more than enough to begin with. In the next part, I am going to share other skills which a good Webmaster needs in their toolset.

Basic Python skills everyone needs to start their coder journey, first part

What is python

Python is a high level computer programming language easy to learn and can be simply put in use by anyone who is passionate about coding. The first time I started reading some python code it felt like i was reading myself, I mean my thoughts converted to code.

Heavily used by Google and Youtube python is becoming very popular among computer programmers all over the world especially in the startup world as it features rapid development making it the swiss army tool for prototyping.

Why learn python

Many of you may ask why learn python and not java or another programming language. This is the right question to ask for a starter in the coding world and I will list some arguments below why one should start learning python as their first computer programming language.

It will take you probably two weeks to learn all the python syntax needed to build real world applications. Or just a few days if you are a passionate reader about these kind of topics.

The fact python is easy to read makes it easy for you as a developer to maintain the code of your project. As the project grows in terms of code you don’t want to come back after your holidays and when looking at the code you have written, not understanding at all how it really works under the hood.

I have had the chance to talk to a python developer who did perl programming for a living back in the days and he told me it is real hard to maintain the code of his old projects. Not hard, but real struggle!

Python is fully Open Source which means that you can look at its implementation code and understand stuff from a lower level perspective.

You can code python on almost any platform. Telling from my experience I have been able to run my python scrips in both Windows and Linux operating systems except for Mac because it is such an expensive toy for me, but for sure you can code python on Mac too.

Python is not just a language. It has a big community behind who is very welcoming and it makes you feel like Home. I am very happy to have met so many python developers in Firenze Italy back in 2013. I felt real love in there.

Some technical knowledge on python

You can notice a python file by the .py extension. Every file that ends with this extension is classified as a python module. For example the following is a python module.

pythongeek.py

The module serves as a container for the python code of our app and we can use the code of a module in other modules by importing it with the import statement like shown below, but do not try to understand this thing right now as this tutorial is just an introduction. I am sure some things may not make sense to you right now and that’s alright.

import pythongeek # imports the pythongeek module

Since python is an intepreted language you will need the official python intepreter to run python code on your machine. In most linux distributions such as Ubuntu it comes installed by default, but in Windows you have to install it yourself.

Having struggled myself with the installation of Python 2.7 on my Windows 7 machine, I decided to write a concise and easy to follow tutorial for everyone on how to download, install and configure Python 2.7.11 on Windows operating system. The tutorial is published on this website, make sure to check it before going any further, especially if you’re using Windows 7 as your main operating system.

Learn and build the basic Python coding skills

Now that you have python available on your machine it is time to build some basic coding skills to build the foundations for further development.

Now that you have a python interpreter in your machine it is time to start some coding. To open the python shell on windows just go to Start and in the search box type python.

Then click on IDLE (Python GUI). The following python graphical shell will come up.

Those who make use of Linux based operating systems, can follow this tutorial too as the python syntax is the same, it does not change per os. So open your terminal, and start to follow.

The above screenshot shows the graphical Python shell supported by Windows machines; for the purpose of this tutorial we are going to use this shell.

Variables

The first thing you need to learn in python is how to declare a variable. You can declare a variable in python like shown below.

a = 5

Where a is the name of the variable and 5 is the value this variable is linked to.

To get the value of the variable you type the name of it and hit Return (Enter) on your keyboard.

python basics

You can also do some maths in Python. The following is a simple arithmetic operation which the Python programming language supports.

a +1

Tuples, Lists, and Dictionaries

Let’s get more pythonic. There are special builtin datatypes in python such as the following:

  • Lists
  • Tuples
  • Dictionaries

There are many others, but for the purpose of this tutorial we will take a look at the ones listed above.

Let’s take a look at lists. For example the following is a list assigned to variable l.

l = [‘python’, ‘geek’, ‘google’, ‘youtube’]

python basics

Lists elements can be accessed and used in a program. For example to access the first element of the list you use the following syntax.

l[0] # where l is the list and 0 is the index of the first element

python basics

So to access the second element you do the following.

l[1]

A list can be updated. For example you can change the first element in our list by doing the following.

l[0] = ‘ruby’

As you can see, when printing the new list the first element is updated.

l

python basics

We will cover lists in more depth in specific tutorials. Now it is time to learn about tuples.

You can define a tuple like shown below.

t = (‘python’, ‘geek’, ‘internet’, ‘skype’)

python basics

The same as in lists you can do indexing in tuples too. For example to get the first element of the above tuple you do the following.

t[0]

python basics

So tuples are like lists? Not really!

Try to update the first element of the tuple we have and see what happens.

t[0] = ‘ruby’

python basics

Let’s move to dictionaries. For example the following is a python dictionary.

d = {‘name’: ‘pythongeek’, ‘occupation’: ‘maths’, ‘age’:13}

python basics

Each item of the dictionary is composed of two elements: a key and a value. For example the first item of our dictionary is composed of the key ‘name’ and the value ‘pythongeek’.

Try the following.

d[‘name’]

python basics

As you can see you access the value of an item in a Python dictionary by its key.

Final thoughts

Before one can code any big application or project in Python, they need to learn and master the basics of this amazing computer programming technology. In the next part, codetheory.in will share more python knowledge one needs in order to progress in their coding journey.