Pages

Wednesday, December 30, 2020

Working with Lists in Python

Lists in Python

Like an array, List is a collection of data (of different data types). Lists are specified using square brackets. 

Lists are very helpful when working with data in Python. Below are some of the features of Lists. 
  • Lists can hold data of different data types. 
  • Lists can be amended.
  • Data in the list can be accessed by using index.
  • Lists can hold duplicate data. 

In this post, we will see how to access, append or remove the data in Lists and how to use different list methods. 

Creating List in Python

Before we go on to different methods of lists, Let us see How to create a List in Python?

Like any other variable in python, List is created when the data is assigned with in square brackets. 

How to create a list in Python

In the above example, 'a_list' is created with the data and 'b_list' is created with no data. 

Accessing the data in a List

How to access the individual elements of Lists? Elements in the Lists can be accessed using index. Index starts with '0' and incremented by '1'. 

Index of a List in Python

Elements of a List can be accessed from the last element with the negative index value. As we can see above, Index of last element would be '-1'. 

If we need to retrieve the second element ("TWO"), index '1' or '-4' needs to be mentioned within square brackets. 

E.g.: 

print(a_list[1]) #prints the second element of a list

print(a_list[-4]) #prints the fourth element from end of a list

Retrieve Index of an element

We have seen how to access the elements using an index, If we know the element and need to know the index, Method 'index()' would be helpful. One thing to note is, it always returns the first index if the element is present multiple times in the list. 

Retrieve index of an element in List - Python

In the above example, '2' is present twice in the list. But, only one index (first occurrence '1') will be returned.

Print list in Python

Adding data to a List

One of the features of a List is the data can be amended. Using append() method, we can add the data to a list. data that needs to be added is to be passed as a parameter to append() method. 

Add new data to a List in Python

In the above example, we are passing "FOUR" to the method 'append()'. This should be added towards end of the list. 

If we notice, "FOUR" is already present in the list. Python allows duplicate data in the list and "FOUR" should be added successfully and printed like the below. 

Print in Python

In the above example, we are only adding one element at a time. If we have another list that needs to be added, this needs to be done with in a loop to add all of these elements using append. What if the list have large number of elements? 

Method 'extend()' can be used to append one list to the other. This method accepts a list (that is to be added) as an argument.

Extend a List in Python

In the above example, data in b_list would be added to a_list. 

Print a list in Python

Removing data from a List

Data can be removed from a list by using remove() method. Similar to the append() method, data that is passed as a parameter would be removed from a List. 

Remove data from a list in Python

In this example, we have two entries with 'FOUR'. And, first occurrence would be deleted from a list. 

Print List in Python

Copy data from one List to other

Like copying data from one variable to other, copying one list to other becomes essential. 

Is copying data from one list to other as simple as copying data from one variable to other? 

Simple answer is 'No'. 

Copying List in Python

In the above example, 
  • Line - 3: 'b_list = a_list', a_list doesn't actually copied over to b_list. b_list would be referencing a_list and any changes to a_list or b_list would reflect for both these. 
  • Lines - 5 & 6: We are appending '6' to b_list and 'SEVEN' to a_list. 
  • Lines - 8 & 9: Both lists should print the same result. 
Print List in Python

To avoid this issue, using copy() method would help to copy the data from one list to other. Let's see how this works using the same example. 

Copy data from one list to other in Python

  • Line - 3: we are using 'a_list.copy()' to copy the data, copy() method doesn't require any arguments.
Print list in Python

One other way to do this is by using function list(). This can be to copy the data from a list, tuple or by passing the data directly. 

Using list function to copy data in Python

In the above example, Lines from 5 to 8 should work in the same way and create list with the data passed.

Clear data from a List

Clearing data from a list can be done using 'clear()' method. This method doesn't require any arguments to be passed and clears the referencing list. 

Clear data from a List in Python

Retrieve the number of occurrences of an element

We know that Python allows duplicate values in the list. If we need to know the number of occurrences of an element in a list, we can use method 'count()'. We need to pass the element value as an argument to this method.

Count the number of occurrences of an element in the list

In the above example, '2' is present '3' times. 

Count the number of occurrences of an element in a List

Retrieve & Delete the value by Index

In the beginning we have seen how to access the values in a list by using index. Let's say if we need to retrieve the value by index and delete this from the list, 'pop()' method is helpful for doing this. 
  • 'pop()' accepts index as an argument and it returns the value in the specific index. 
  • Once the value is deleted, Python would automatically adjust the index, value in the next position would now be referred with this index. 
Retrieve & Delete the value from a list using pop() in Python

In the above example,
  • Line - 4: value '2' (at index 1) should be returned and deleted from the list.
  • Line - 5: value '3' would now be at index '1' and should be returned and deleted from the list.
Print list in Python

Sorting a List

Lists doesn't necessarily hold the data in the order (ascending or descending). But, if we need to sort the data in a list, Method 'sort()' is useful. With default parameters, this method sorts the data in ascending order and by passing 'reverse=True' data is updated in reverse order. And, method reverse() is useful to sort the data in reverse order.

Sort a list in Python



In the above example, 
  • Line-3: With no arguments passed, list would be sorted in ascending order.
  • Line-8: with 'reverse=True', list would be sorted in descending order. passing 'reverse=False' would work like default and data is sorted in reverse order.
  • Line-14: Data would be sorted in reverse order of index.
Print list in Python

One thing to note here is, sort() would only work with data of same data type in a list. If there are different data types present (like int and str), sort() would fail.

The above 'sort()' method updates the same list. If we need to sort the data and move it to the new list (and leave the original as is), we can use the function 'sorted()'. This accepts a list as an argument and returns sorted list. There is an optional parameter 'reverse', by passing 'True' to this parameter would sort the data in descending order.

Sorted() in Python


Print list in Python

Hope the above details were a bit of help to you in understanding more about Lists in Python.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Wednesday, December 23, 2020

Operators in Python

Operators

Operator is a symbol that is used to perform specific operations like mathematical, relational or logical operations. 

There are different types of operators. Below are some the most common operators

  • Mathematical Operators.
  • Assignment Operators.
  • Relational Operators.
  • Logical Operators.

Apart from these, there are couple of more types. 

  • Identity Operators.
  • Membership Operators.

Let's have a look at each of these. 

Mathematical Operators

Mathematical operators are used to perform mathematical operations (as name states) with numeric values. 

These are operators like '+' Addition, '-' Subtraction, '*' Multiplication, '/' Division, '%' Modulus, '//' Floor Division and '**' Exponentiation.

a = 10

b = 5

c = a + b 
# Addition of two variables, Result would be c = 15

c = a - b 
# Subtraction of second variable from first variable, Result would be c = 5

c = a * b 
# Multiplication of two variables, Result would be c = 50

c = a / b 
# Division, Divides first variable with second variable, Result would be c = 2.0. Result for the division operation would always be float.

c = a % b 
# Modulus, Returns the reminder after dividing first variable with second variable. Result would be c = 0. If a = 11, b = 5, then Result would be c = 1

c = a // b 
# Floor Division, Divides first variable (a) with second variable (b) and returns the whole number only. Result would be c = 2

c = a ** b 
# Exponentiation, Calculating the first variable (a) with the power of second variable (b), Result would be c = 10000.

Assignment Operators

Assignment Operators are used to assign value to a variable. 

One of the assignment operators is '=' (equal to) to assign a value to a variable. In python, a variable is declared when a value is assigned. 

a = 10 
# This defines a integer variable 'a' and assigns a value '10'

Below are the few other assignment operators. 

*Considering the current value of 'a' as '10' for all of these examples.

'+=' Adds the value on the right side to the current value of the variable. 

a += 5 
# adds 5 to the current value of 'a' (i.e., 10) and assigns it to 'a'. This is same as 'a = a + 5'.

'-=' Subtracts the value on the right side from the current value of the variable. 

a -= 5 
# subtracts 5 from the current value of 'a' (i.e., 10) and assigns it to 'a'. This is same as 'a = a - 5'.
  
'*=' Multiplies the value on the right side with the current value of the variable. 

a *= 5 
# multiplies 5 with the current value of 'a' (i.e., 10) and assigns it to 'a'. This is same as 'a = a * 5'.

'/=' Divides the current value of the variable with the value on the right side. 

a /= 5
# divides the current value of 'a' (i.e., 10) with 5 and assigns to 'a'. This is same as 'a = a / 5'.

'%=' Divides the current value of the variable with the value on the right side to calculate the remainder. 

a %= 5 
# divides the current value of 'a' (i.e., 10) with 5 and assigns the remainder to 'a'. This is same as 'a = a % 5'.

'//=' Divides the current value of the variable with the value on the right side and assign the resulting whole number

a //= 5 
# (Floor) divide the current value of 'a' (i.e., 10) with '5' and assigns it to 'a'. This is same as 'a = a // 5'.

'**=' Calculate the exponent of the variable to the power of value on the right side. 

a **= 5 
# Calculate the current value of 'a' (i.e., 10) to the power of 5 and assigns it to 'a'. This is same as 'a = a ** 5'.

Relational Operators

Relational Operators are used to compare the relation between two variables (e.g. greater than, less than, equal to...).

Below are the Relational operators. 
  • Equal To (==), used to check if the variables on either sides are equal (a == b). Returns True if equal and False if not equal.
  • Not Equal To (!=), used to check if the variables on either sides are not equal (a != b). Returns True if not equal and False if equal.
  • Greater than (>), used to check if the left side variable is greater than the right side variable (a > b). Returns True if greater and False if not greater. 
  • Greater than or Equal to (>=), used to check if the left side variable is either greater or equal to right side variable (a >= b). Returns True if greater than or equal and False if not.
  • Less than (<), used to check if the left side variable is less than the right side variable (a < b). Returns True if less and False if not less. 
  • Less than or Equal to (<=), used to check if the left side variable is either less or equal to right side variable (a <= b). Returns True if less than or equal and False if not.

Logical Operators

Logical operators are used to combine multiple conditions and returns if the result is True or False. 

  • 'and', returns True if conditions on either sides are True and returns False if at least one of them is False.
(a > b) and (c > d)
# if both conditions (a > b) and (c > d) are True, then the result would be True. If at least one of them is False, then result would be False.

  • 'or', returns True if one of the condition is True and returns False if both of them are False. 
(a > b) or (c > d)
# if at least one of the condition (a > b) or (c > d) are True, then result would be True. If both conditions are False, then result would be False. 

  • 'not', returns the opposite value of the current condition. If the condition is True, not would return False and vice versa.
not (a > b) 
# if (a > b) is True, then the result would False. if (a > b) is False, then result would be True.

Identity Operators

Identity Operators are used to identify if a value belongs to particular class or type. 

  • 'is', returns True if the type (or value) on the left side matches with the type (or value) mentioned on the right side. 
E.g.:

a = 10
print(type(a) is int) # prints True, as the data type of 'a' is int and the condition is satisfied. 

a = 10
b = 11 
print(a is b) # prints False, as the values of 'a' and 'b' aren't same.

  • 'is not', returns False if the type (or value) on the left side doesn't match with the type (or value) mentioned on the right side.
E.g.:

a = 10
print(type(a) is not int) # prints False, as the data type of 'a' is int and the condition is not satisfied. 

a = 10
b = 11 
print(a is not b) # prints True, as the values of 'a' and 'b' aren't same.

Membership Operators

Membership operators are used to check if the value on the left side is part of the sequence (list or tuples). 

  • 'in', returns True if the left side value is part of sequence mentioned on the right side. returns False if not part of sequence mentioned on the right side.
E.g.:

a = [1, 2, 3]
b = 2

print(b in a) # prints True as '2' is part of list 'a'

  • 'not in', returns False if the left side value is part of sequence mentioned on the right side. returns True if not part of sequence mentioned on the right side.
E.g.:

a = [1, 2, 3]
b = 2

print(b not in a) # prints False as '2' is part of list 'a' 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Friday, December 18, 2020

Variables in Python

Variables

Variables are like containers holding data from a memory location. 

In different terms, Variable is used to retrieve/store value from/to memory. 

In programming languages, Variables are defined with specific data type and are used to any kind of processing related to the data type. 

How are variables defined in Python? There is no explicit declaration for variables in Python like most other languages. Variable is automatically created the moment the data is assigned. 

How does python know what data type the variable should be created with? Python creates the variables in the run time based on the data assigned and variable is created based on the type of the data is assigned. It is easy to understand with some examples. 

E.g.

Let's assign an integer to 'first_variable' and string to 'second_variable'. 

Variables in Python

How do we know the data type of a variable? 'type' function would return the data type of a variable. 

Let's try to print the data in these two variables along with data type of the variables. 

Variables in Python

  • Line - 6: We are passing first_variable, type(first_variable) to print function. This should print the data stored in the variable and corresponding data type. 
  • Line - 11: We are passing second_variable, type(second_variable) to print function. This should print the data stored in the variable and corresponding data type.
Variables in Python

Type function has returned the data type along with the text 'class'. So, Would it always be the same? How should we check the data type inside the program (instead of printing)?

We still need to use the type function, and compare it with data type we need to check for. 

Variables in Python

  • Line - 13: We are checking if the type of the variable is 'int' and it is not enclosed with in quotes. This would consider this as a data type. Data type shouldn't be enclosed with in quotes (if it is it would consider as string and would execute else part).

Variables in Python

This would be the same for any other data type. Just use 'str' for String, 'float' for Float, 'list' for List...

We now know that Python assigns data type automatically when a value is assigned. What would happen if the data (of different data types) is assigned multiple times?

Let's see,

Variables in Python

Here we have assigned integer (line - 3) and string (line - 8) to first_variable and running print statement after each assignment. 

Variables in Python

We can see that first print statement has printed the data type as 'int' and second print statement has printed the data type as 'str'. So, data type of a variable can be changed based on the value assigned. 

Are there any constraints on what name to be used for a variable? Yes, there are few constraints on how a variable should be named. 

  • Variable name should start with a letter or underscore and cannot start with a number.
  • No special characters are allowed in a variable name (except underscore). 
  • Variable names are case sensitive (E.g.: First and first would be considered as two different variables).


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Monday, December 14, 2020

Data Types in Python

Data Types


Data types are the key for any programming language. Various data types are present to do different operations and variables can store the corresponding data.

One of the greatest advantage for python is it is dynamically typed (i.e., data type is assigned during the run time based on the value assigned). 

Unlike most of the programming languages, there is no need to define a variable with data type explicitly mentioned. 

Below are different categories of data types in python. 

  • Numeric
  • Sequence 
  • Boolean
  • Dictionary
  • Set

Let's have a look at the data types in each of these category. 

Numeric:

  • int - integer data type, to hold the whole numbers. No decimal values are stored in integer data type. This can hold both Positive and Negative values.
  • float - float data type, to hold the numbers along with decimal values. This can hold both Positive and Negative values.
  • complex - complex data type, complex numbers are a combination of real numbers and imaginary number (multiplied with 'j' (square root of -1)).

Numeric data types in python

Sequence:

Data stored as a sequence in a variable (or collection of data of same data type or different data type). 
  • str - string data type, String is considered as collection (or array) of characters.
  • list - List is a collection of data, This can hold data of different data types. Lists are specified in square brackets.
  • tuple - Tuple is a collection of data, This can hold data of different data types. Tuples are specified in round brackets.

Sequence data types in Python

We can see that List and Tuple both look same except the way they are defined. 

So, What's the difference between List & Tuple? Data in List can be updated, removed or new data can be added to the list. Where as Once defined, data in the tuple cannot be amended.

Tuple is the best choice when there is a set of values and they don't change through out the program (like constants) and Lists are flexible and can be used for any kind of transaction processing. 

How can we access individual data elements? Individual element of a string, list or tuple can be accessed using index. Index starts from '0'. 

Sequence data types in Python


Same way, data can be accessed in reverse as well, Last element would represent the index '-1'. 

Sequence data types in Python

Boolean:

  • bool - Boolean data type, to hold the boolean value i.e., True or False. This can only take 'True' or 'False' (case sensitive).
Boolean data type in Python

Dictionary:

  • dict - Dictionary data type, this hold a set of data with key and corresponding value separated by ':'. Data in dictionary can be accessed by using key and it has no corresponding index. Data in dictionary is enclosed in curly brackets.

Dictionary data type in Python

Set:

  • set - Set is a un ordered collection of data of different data types. Data cannot be accessed by using index. But, the elements of a set can be access through loop or by value. Data to a set can be assigned from List or tuple using 'set' function. 
Set data type in Python

We have seen how to assign the data to a variable and how it determines the data type based on the data assigned in the code samples above. But, haven't really seen much about variables and I will share more details on variables in the next post.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Saturday, December 12, 2020

Python Print Function - What parameters does it accept?

Print Function in Python


The first thing most of the developers would do is to try printing "Hello World" when learning new programming language. 

We have run our first python script to print "Hello World, My First Python Script" in our Getting Started with Python post. Have a quick look at this post if you haven't already seen. 

We will now see more about print() function in Python.

So, What's more to know about print? Isn't this as simple as passing a message to print? 

Yes, one way it is as simple as passing the message in the parameters as an argument and the message would be printed. 

print function in python

In the above script, we have just passed the message to be printed to the print function and it has printed the message to the console. 

print in python
Okay, everything looks fine? Yes, almost. If we notice, there is a line printed after the message before it actually say 'Process finished with exit code 0'

Isn't this normal? And, Can we actually print the message without without writing a new line? 

Firstly, This is normal and that's how python's print() function supposed to work with default parameters. And, probably that's the way print() function is mostly used in Python. 

To the next question, Yes we can print the message without writing a new line, so the message would appear as below.

print in python

How do we do this? There are some optional parameters to print() function which would control the way message is printed. Let's have a look at these.

ParameterMandatory/
Optional
Description
valuesMandatoryActual message/data to be printed. This can be a single value or multiple values.
sepOptionalSeparator, If multiple values are passed, this parameter would be used to determine how the values are separated. Default value is ' ' (Blanks)
endOptionalEnd value, Specify what needs to be printed at the end. Default value is '\n' (new line)
fileOptionalObject with write method. default value is stdout.
flushOptionalBoolean value, True - if the output is flushed, False - if the output is buffered. Default value is ' ' (Blanks)

Syntax of print():

print(values, sep, end, file, flush)

Now, let's look at the use of each of these parameters. 

values

In the above example, we have used the full text as a single argument. Let's see if we can pass this as two different arguments and how this would be printed.

print in python

We have passed two separate arguments to be printed. Let's see how this is printed. 

print in python

This has printed messages in the two arguments by separating them with ' '. This is because of the default value on parameter 'sep'.

sep

In the above example, default value on 'sep' was used to separate the data passed in the arguments. Let's now see how this is printed if we pass a value against this parameter. 

print in python

We are now passing another parameter 'sep'. Let's see how this is printed. 

print in python

Separator has now been printed. This becomes handy when we have multiple messages to be printed with a separator. Using 'sep' would avoid having to concatenate all the messages. 

The result is printed with new line. This is because of the default value (\n) on 'end' parameter. 

end


Let's see how the result would be printed if we pass different value to parameter 'end'. 

print in python

In the above example, we are passing '.' as separator. The result should now be printed with '.' at the end and no new lines should be printed. 

print in python

file

'file' parameter accepts an object with write method. Default value for this is 'sys.stdout'. Message is printed to stdout if we use the default.

'stdout' has write method and prints the message where ever the python script is running (like command line or IDE), in the examples we are using, it is printed on IDE. 

We'll see more on this parameter later with some examples. 

flush

Before we actually see what flush does, we go back little to the 'end' parameter. Default value for 'end' is new line. 

  • When print() is executed with default values, message is printed immediately (flushed) as soon as print statement is run.
  • When print() is executed with blanks/null for 'end' parameter, message isn't immediately printed after executing the print statement.
Why is that? Python would store the message in the buffer and prints when it reaches new line.

In the second scenario, end of the message is blanks/null, so python retains message in the buffer and prints when the program is ended or when the new line is printed further down in the program. 

How do we deal with this? If the message is to be printed immediately after print statement without having to print new line, 'flush' would be helpful. 

passing 'True' (flush = True) would print the message immediately. It is better explained with an example.

print in python

In the above scenario, "Hello World" isn't printed until print of "My First Python Statement." is executed. 

This can be handled by using flush parameter.

print in python

In Line - 2, we have mentioned 'flush=True', this would prints the message 'Hello World" immediately without having to wait for the next statement. 


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Wednesday, December 9, 2020

Getting Started with Python

Python


Python is an interpreted (not compiled), high level and general purpose programming language. Python supports both Object oriented and Structured programming models.

Python is the world's most popular programming language in 2020. Probably this would continue to be the same for another decade or so.

Before we start on with Python, There are some basic questions that comes to most of our mind.

  • Why should we learn Python?
  • What makes Python different from other Programming Languages? 
  • Why is it so popular? 

Probably it's the same answer for all these questions. Let's see what makes Python so special. 

  • High level programming language with simple syntax and easy to read, write and learn. This would result in Increased Productivity.
  • Python is an interpreted language and executes the code line by line in run time. This makes it easier to analyze and debug in case of any errors. 
  • Python has huge standard library, this makes it easier for development to pick the required function rather than having to develop it. 
  • Dynamically typed, Python automatically assigns the data type to a variable in the run time based on the value being assigned. 
  • Independent of Platform, Python code can run on different Operating Systems like Windows, Mac and Linux.

Getting Started


So, what do we need to get started with python? 

  • Installation
  • Text Editor/IDE

Installation


Some of the computers may already have python installed already. To check the version of python installed, run the below command in Command Line (or Terminal on Mac). 

python

Python

Command 'python' by default look for python2. In the above screenshot, highlighted is the python version installed (Python 2.7.16).

To check if Python 3 is installed, run below command in the terminal. 

python3

Python 3

Python commands can be directly run from the terminal. 

E.g.:

Let's print "Hello World" from terminal. 

print("Hello World, My First Python Statement")


Python Script

Text Editor/IDE:

Program is a set of executable statements and we can't always run them from command line. 

There are various Text Editors and IDEs which are tailored to work with Python script. These would make working with python much easier. 

I prefer to use 'PyCharm' and there are many other IDEs. 

Now, let's create a python script main.py with 'print' statement and run. 

print - python

When we run this script, this prints the text we have provided to print. 

print - python

We have successfully run our first Python script. Happy Learning... 

If you have any suggestions or comments, Please leave a comment or email me using the Contact form.

Exception Handling in Python (try - except-else-finally)

Exception Handling in Python Exception handling is key for any programming language. When an exception occurs Python interpreter stops execu...