- Python is developed by Guido van Rossum.
- Guido van Rossum started implementing Python in 1989.
- Python is a very simple programming language so even if you are new to programming, you can learn python without facing any issues.
Interesting fact: Python is named after the comedy television show Monty Python’s Flying Circus. It is not named after the Python snake.
Features of Python programming language
What Can You Do with Python?
There are so many applications of Python, here are some of the them.
- Web development
- Machine Learning
- Data Analysis
- Scripting
- Game Development
- Desktop Application
How to install Python
Install PyCharm Python IDE in Windows, Mac OS X, Linux/Unix
First Python Project in PyCharm IDE
Comments in Python Programming
Types of Comments in Python
There are two types of comments in Python.
1. Single line comment
In python we use # special character to start the comment. Lets take few examples to understand the usage.
# This is just a comment. Anything written here is ignored by Python
2. Multiple line comment
Multi-line comment:
To have a multi-line comment in Python, we use triple single quotes at the beginning and at the end of the comment, as shown below.
'''
This is a
multi-line
comment
'''
Python Keywords and Identifiers
- Keywords are the reserved words in Python.
- We cannot use a keyword as a variable name, function name or any other identifier.
- They are used to define the syntax and structure of the Python language.
- In Python, keywords are case sensitive.
Python Identifiers
- An identifier is a name given to entities like class, functions, variables, etc.
- It helps to differentiate one entity from another.
Rules for writing identifiers
- Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all are valid example.
- An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
Keywords cannot be used as identifiers.
global = 1
Output
File “<interactive input>”, line 1
global = 1
^
- SyntaxError: invalid syntax
We cannot use special symbols like !, @, #, $, % etc. in our identifier.
a@ = 0
Output
File “<interactive input>”, line 1
a@ = 0
^
- SyntaxError: invalid syntax
- An identifier can be of any length.
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character (\). For example:
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
This is an explicit line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }. For instance, we can implement the above multi-line statement as:
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ] and { }. For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over tabs. Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
- The enforcement of indentation in Python makes the code look neat and clean.
- This results in Python programs that look similar and consistent.
- Indentation can be ignored in line continuation, but it’s always a good idea to indent.
- It makes the code more readable. For example:
if True:
print('Hello')
a = 5
and
if True: print(‘Hello’); a = 5
both are valid and do the same thing, but the former style is clearer.
Assigning multiple values to multiple variables
a, b, c = 5, 3.2, “Hello”
If we want to assign the same value to multiple variables at once, we can do this as:
x = y = z = “same”
Assigning value to constant in Python
In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.
Example 3: Declaring and assigning value to a constant
Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant
print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
List of Python Operators
Python operators allow us to do common processing on variables. We will look into different types of operators with examples and also operator precedence. They are the special symbols that can manipulate the values of one or more operands.
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.
Operator | Meaning | Example |
+ | Add two operands or unary plus | x + y+ 2 |
– | Subtract right operand from the left or unary minus | x – y- 2 |
* | Multiply two operands | x * y |
/ | Divide left operand by the right one (always results into float) | x / y |
% | Modulus – remainder of the division of left operand by the right | x % y (remainder of x/y) |
// | Floor division – division that results into whole number adjusted to the left in the number line | x // y |
** | Exponent – left operand raised to the power of right | x**y (x to the power y) |
Example 1: Arithmetic operators in Python
x = 15
y = 4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
Output
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators
Comparison operators are used to compare values. It returns either True or False according to the condition.
Operator | Meaning | Example |
> | Greater than – True if left operand is greater than the right | x > y |
< | Less than – True if left operand is less than the right | x < y |
== | Equal to – True if both operands are equal | x == y |
!= | Not equal to – True if operands are not equal | x != y |
>= | Greater than or equal to – True if left operand is greater than or equal to the right | x >= y |
<= | Less than or equal to – True if left operand is less than or equal to the right | x <= y |
Example 2: Comparison operators in Python
x = 10
y = 12
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
Output
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
Logical operators
Logical operators are the and, or, not operators.
Operator | Meaning | Example |
and | True if both the operands are true | x and y |
or | True if either of the operands is true | x or y |
not | True if operand is false (complements the operand) | not x |
Example 3: Logical Operators in Python
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Output
x and y is False
x or y is True
not x is False
Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator | Meaning | Example |
& | Bitwise AND | x & y = 0 (0000 0000) |
| | Bitwise OR | x | y = 14 (0000 1110) |
~ | Bitwise NOT | ~x = -11 (1111 0101) |
^ | Bitwise XOR | x ^ y = 14 (0000 1110) |
>> | Bitwise right shift | x >> 2 = 2 (0000 0010) |
<< | Bitwise left shift | x << 2 = 40 (0010 1000) |
Assignment operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.
Operator | Example | Equivalent to |
= | x = 5 | x = 5 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x – 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
//= | x //= 5 | x = x // 5 |
**= | x **= 5 | x = x ** 5 |
&= | x &= 5 | x = x & 5 |
|= | x |= 5 | x = x | 5 |
^= | x ^= 5 | x = x ^ 5 |
>>= | x >>= 5 | x = x >> 5 |
<<= | x <<= 5 | x = x << 5 |
Special operators
Python language offers some special types of operators like the identity operator or the membership operator. They are described below with examples.
Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical.
Operator | Meaning | Example |
is | True if the operands are identical (refer to the same object) | x is True |
is not | True if the operands are not identical (do not refer to the same object) | x is not True |
Example 4: Identity operators in Python
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
Output
False
True
False
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory although they are equal.
Membership operators
in and not in are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
Operator | Meaning | Example |
in | True if value/variable is found in the sequence | 5 in x |
not in | True if value/variable is not found in the sequence | 5 not in x |
Example #5: Membership operators in Python
x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False
print('a' in y)
Output
True
True
True
False
Here, ‘H’ is in x but ‘hello’ is not present in x (remember, Python is case sensitive). Similarly, 1 is key and ‘a’ is the value in dictionary y. Hence, ‘a’ in y returns False.
Data Types
Python Numbers
Python supports integers, floats and complex numbers.
An integer is a number without decimal point for example 5, 6, 10 etc.
A float is a number with decimal point for example 6.7, 6.0, 10.99 etc.
A complex number has a real and imaginary part for example 7+8j, 8+11j etc.
Python example to find the class(data type) of a number
We can use the type() function to find out the class of a number. An integer number belongs to int class, a float number belongs to float class and a complex number belongs to complex class.
# program to find the class of a number
# int
num = 100
print("type of num: ",type(num))
The isinstance() function
The isinstance() functions checks whether a number belongs to a particular class and returns true or false based on the result.
For example:
isinstance(num, int) will return true if the number num is an integer number.
isinstance(num, int) will return false if the number num is not an integer number.
Example of isinstance() function
num = 100
# true because num is an integer
print(isinstance(num, int)) //true
# false because num is not a float
print(isinstance(num, float)) //false
Python numeric data type is used to hold numeric values like;
- int – holds signed integers of non-limited length.
- float– holds floating precision numbers and it’s accurate up to 15 decimal places.
- complex– holds complex numbers.
In Python, we need not declare a datatype while declaring a variable like C or C++. We can simply just assign values in a variable. But if we want to see what type of numerical value is it holding right now, we can use type(), like this:
#create a variable with integer value.
a=100
print("The type of variable having value", a, " is ", type(a))
#create a variable with float value.
b=10.2345
print("The type of variable having value", b, " is ", type(b))
#create a variable with complex value.
c=100+3j
print("The type of variable having value", c, " is ", type(c))
If you run the above code you will see output like the below image.
Python List with examples
A list is a data type that allows you to store various types data in it. List is a compound data type which means you can have different-2 data types under a list, for example we can have integer, float and string items in a same list.
1. Create a List in Python
Lets see how to create a list in Python. To create a list all you have to do is to place the items inside a square bracket [] separated by comma ,.
# list of floats
num_list = [11.22, 9.9, 78.34, 12.0]
# list of int, float and strings
mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"]
# an empty list
nodata_list = []
As we have seen above, a list can have data items of same type or different types. This is the reason list comes under compound data type.
2. Accessing the items of a list
Syntax to access the list items:
list_name[index]
Example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# prints 11
print(numbers[0])
Points to Note:
1. The index cannot be a float number.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[1.0])
Output:
TypeError: list indices must be integers or slices, not float
2. The index must be in range to avoid IndexError. The range of the index of a list having 10 elements is 0 to 9, if we go beyond 9 then we will get IndexError. However if we go below 0 then it would not cause issue in certain cases, we will discuss that in our next section.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[6])
Output:
IndexError: list index out of range
3. Negative Index to access the list items from the end
Unlike other programming languages where negative index may cause issue, Python allows you to use negative indexes. The idea behind this to allow you to access the list elements starting from the end. For example an index of -1 would access the last element of the list, -2 second last, -3 third last and so on.
3.1 Example of Negative indexes in Python
# a list of strings
my_list = ["hello", "world", "hi", "bye"]
# prints "bye"
print(my_list[-1])
# prints "world"
print(my_list[-3])
# prints "hello"
print(my_list[-4])
Output:
bye
world
hello
4. How to get a sublist in Python using slicing
We can get a sublist from a list in Python using slicing operation. Lets say we have a list n_list having 10 elements, then we can slice this list using colon : operator. Lets take an example to understand this:
We can get a sublist from a list in Python using slicing operation. Lets say we have a list n_list having 10 elements, then we can slice this list using colon : operator. Lets take an example to understand this:
4.1 Slicing example
# list of numbers
n_list = [1, 2, 3, 4, 5, 6, 7]
# list items from 2nd to 3rd
print(n_list[1:3])
# list items from beginning to 3rd
print(n_list[:3])
# list items from 4th to end of list
print(n_list[3:])
# list items from 0 to 3 and skip by 1
print(n_list[0:3:2])
# Whole list
print(n_list[:])
5. List Operations
There are various operations that we can perform on Lists.
5.1 Addition
There are several ways you can add elements to a list.
# list of numbers
n_list = [1, 2, 3, 4]
# 1. adding item at the desired location
# adding element 100 at the fourth location
n_list.insert(3, 100)
# list: [1, 2, 3, 100, 4]
print(n_list)
# 2. adding element at the end of the list
n_list.append(99)
# list: [1, 2, 3, 100, 4, 99]
print(n_list)
# 3. adding several elements at the end of list
# the following statement can also be written like this:
# n_list + [11, 22]
n_list.extend([11, 22])
# list: [1, 2, 3, 100, 4, 99, 11, 22]
print(n_list)
Output:
[1, 2, 3, 100, 4]
[1, 2, 3, 100, 4, 99]
[1, 2, 3, 100, 4, 99, 11, 22]
5.2 Update elements
We can change the values of elements in a List. Lets take an example to understand this:
# list of numbers
n_list = [1, 2, 3, 4]
# Changing the value of 3rd item
n_list[2] = 100
# list: [1, 2, 100, 4]
print(n_list)
# Changing the values of 2nd to fourth items
n_list[1:4] = [11, 22, 33]
# list: [1, 11, 22, 33]
print(n_list)
Output:
[1, 2, 100, 4]
[1, 11, 22, 33]
5.3 Delete elements
# list of numbers
n_list = [1, 2, 3, 4, 5, 6]
# Deleting 2nd element
del n_list[1]
# list: [1, 3, 4, 5, 6]
print(n_list)
# Deleting elements from 3rd to 4th
del n_list[2:4]
# list: [1, 3, 6]
print(n_list)
# Deleting the whole list
del n_list
Output:
[1, 3, 4, 5, 6]
[1, 3, 6]
5.4 Deleting elements using remove(), pop() and clear() methods
remove(item): Removes specified item from list.
pop(index): Removes the element from the given index.
pop(): Removes the last element.
clear(): Removes all the elements from the list.
# list of chars
ch_list = ['A', 'F', 'B', 'Z', 'O', 'L']
# Deleting the element with value 'B'
ch_list.remove('B')
# list: ['A', 'F', 'Z', 'O', 'L']
print(ch_list)
# Deleting 2nd element
ch_list.pop(1)
# list: ['A', 'Z', 'O', 'L']
print(ch_list)
# Deleting all the elements
ch_list.clear()
# list: []
print(ch_list)
Output:
['A', 'F', 'Z', 'O', 'L']
['A', 'Z', 'O', 'L']
[]
Python Strings
A string is usually a bit of text (sequence of characters). In Python we use ” (double quotes) or ‘ (single quotes) to represent a string. In this guide we will see how to create, access, use and manipulate strings in Python programming language.
1. How to create a String in Python
There are several ways to create strings in Python.
1. We can use ‘ (single quotes), see the string str in the following code.
2. We can use ” (double quotes), see the string str2 in the source code below.
3. Triple double quotes “”” and triple single quotes ”’ are used for creating multi-line strings in Python. See the strings str3 and str4 in the following example.
# lets see the ways to create strings in Python
str = 'beginnersbook'
print(str)
str2 = "Chaitanya"
print(str2)
# multi-line string
str3 = """Welcome to
Beginnersbook.com"""
print(str3)
str4 = '''This is a tech
blog'''
print(str4)
Output:
beginnersbook
Chaitanya
Welcome to
Beginnersbook.com
This is a tech
blog
2. How to access strings in Python
A string is nothing but an array of characters so we can use the indexes to access the characters of a it. Just like arrays, the indexes start from 0 to the length-1.
You will get IndexError if you try to access the character which is not in the range. For example,
if a string is of length 6 and you try to access the 8th char of it then you will get this error.
You will get TypeError if you do not use integers as indexes, for example if you use a float as an index then you will get this error.
str = "Kevin"
# displaying whole string
print(str)
# displaying first character of string
print(str[0])
# displaying third character of string
print(str[2])
# displaying the last character of the string
print(str[-1])
# displaying the second last char of string
print(str[-2])
Output:
Kevin
K
v
n
i
3. Python String Operations
Lets see the operations that can be performed on the strings.
3.1. Getting a substring in Python – Slicing operation
We can slice a string to get a substring out of it. To understand the concept of slicing we must understand the positive and negative indexes in Python (see the example above to understand this). Lets take a look at the few examples of slicing.
str = "Beginnersbook"
# displaying whole string
print("The original string is: ", str)
# slicing 10th to the last character
print("str[9:]: ", str[9:])
# slicing 3rd to 6th character
print("str[2:6]: ", str[2:6])
# slicing from start to the 9th character
print("str[:9]: ", str[:9])
# slicing from 10th to second last character
print("str[9:-1]: ", str[9:-1])
Output:
The original string is: Beginnersbook
str[9:]: book
str[2:6]: ginn
str[:9]: Beginners
str[9:-1]: boo
3.2 Concatenation of strings in Python
The + operator is used for string concatenation in Python. Lets take an example to understand this:
tr1 = "One"
str2 = "Two"
str3 = "Three"
# Concatenation of three strings
print(str1 + str2 + str3)
Output:
OneTwoThree
Note: When + operator is used on numbers it adds them but when it used on strings it concatenates them. However if you try to use this between string and number then it will throw TypeError.
For example:
s = "one"
n = 2
print(s+n)
Output:
TypeError: must be str, not int
3.3 Repetition of string – Replication operator
We can use * operator to repeat a string by specified number of times.
str = "ABC"
# repeating the string str by 3 times
print(str*3)
Output:
ABCABCABC
3.4 Python Membership Operators in Strings
in: This checks whether a string is present in another string or not. It returns true if the entire string is found else it returns false.
not in: It works just opposite to what “in” operator does. It returns true if the string is not found in the specified string else it returns false.
str = "Welcome to beginnersbook.com"
str2 = "Welcome"
str3 = "Chaitanya"
str4 = "XYZ"
# str2 is in str? True
print(str2 in str)
# str3 is in str? False
print(str3 in str)
# str4 not in str? True
print(str4 not in str)
Output:
True
False
True
3.5 Python – Relational Operators on Strings
The relational operators works on strings based on the ASCII values of characters.
The ASCII value of a is 97, b is 98 and so on.
The ASCII value of A is 65, B is 66 and so on.
str = "ABC"
str2 = "aBC"
str3 = "XYZ"
str4 = "XYz"
# ASCII value of str2 is > str? True
print(str2 > str)
# ASCII value of str3 is > str4? False
print(str3 > str4)
Output:
True
False
Accessing characters in Python
In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed as an index, float or other types will cause a TypeError.
# Python Program to Access
# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
Initial String:
GeeksForGeeks
First character of String is:
G
Last character of String is:
s
Skip character sequence
Var =”santosh”
print(var[0:4:2])
Output:-
sn - it will print from 0 to 3 with index skip by 1
Python Tuple with example
In Python, a tuple is similar to List except that the objects in tuple are immutable which means we cannot change the elements of a tuple once assigned. On the other hand, we can change the elements of a list.
1. Tuple vs List
1. The elements of a list are mutable whereas the elements of a tuple are immutable.
2. When we do not want to change the data over time, the tuple is a preferred data type whereas when we need to change the data in future, list would be a wise option.
3. Iterating over the elements of a tuple is faster compared to iterating over a list.
4. Elements of a tuple are enclosed in parenthesis whereas the elements of list are enclosed in square brackets.
2. How to create a tuple in Python
To create a tuple in Python, place all the elements in a () parenthesis, separated by commas. A tuple can have heterogeneous data items, a tuple can have string and list as data items as well.
2.1 Example – Creating tuple
In this example, we are creating few tuples. We can have tuple of same type of data items as well as mixed type of data items. This example also shows nested tuple (tuples as data items in another tuple).
# tuple of strings
my_data = ("hi", "hello", "bye")
print(my_data)
2.2 Empty tuple:
# empty tuple
my_data = ()
2.3 Tuple with only single element:
Note: When a tuple has only one element, we must put a comma after the element, otherwise Python will not treat it as a tuple.
# a tuple with single data item
my_data = (99,)
If we do not put comma after 99 in the above example then python will treat my_data as an int variable rather than a tuple.
3. How to access tuple elements
We use indexes to access the elements of a tuple. Lets take few example to understand the working.
3.1 Accessing tuple elements using positive indexes
We can also have negative indexes in tuple, we have discussed that in the next section. Indexes starts with 0 that is why we use 0 to access the first element of tuple, 1 to access second element and so on.
# tuple of strings
my_data = ("hi", "hello", "bye")
# displaying all elements
print(my_data)
# accessing first element
# prints "hi"
print(my_data[0])
# accessing third element
# prints "bye"
print(my_data[2])
Output:
('hi', 'hello', 'bye')
hi
bye
Note:
1. TypeError: If you do not use integer indexes in the tuple. For example my_data[2.0] will raise this error. The index must always be an integer.
2. IndexError: Index out of range. This error occurs when we mention the index which is not in the range. For example, if a tuple has 5 elements and we try to access the 7th element then this error would occurr.
3.2 Negative indexes in tuples
Similar to list and strings we can use negative indexes to access the tuple elements from the end.
-1 to access last element, -2 to access second last and so on.
my_data = (1, 2, “Kevin”, 8.9)
my_data = (1, 2, "Kevin", 8.9)
# accessing last element
# prints 8.9
print(my_data[-1])
# prints 2
print(my_data[-3])
Output:
8.9
2
3.3 Accessing elements from nested tuples
Lets understand how the double indexes are used to access the elements of nested tuple. The first index represents the element of main tuple and the second index represent the element of the nested tuple.
In the following example, when I used my_data[2][1], it accessed the second element of the nested tuple. Because 2 represented the third element of main tuple which is a tuple and the 1 represented the second element of that tuple.
my_data = (1, "Steve", (11, 22, 33))
# prints 'v'
print(my_data[1][3])
# prints 22
print(my_data[2][1])
Output:
v
22
4. Operations that can be performed on tuple in Python
Lets see the operations that can be performed on the tuples in Python.
4.1 Changing the elements of a tuple
We cannot change the elements of a tuple because elements of tuple are immutable. However we can change the elements of nested items that are mutable. For example, in the following code, we are changing the element of the list which is present inside the tuple. List items are mutable that’s why it is allowed.
my_data = (1, [9, 8, 7], "World")
print(my_data)
# changing the element of the list
# this is valid because list is mutable
my_data[1][2] = 99
print(my_data)
# changing the element of tuple
# This is not valid since tuple elements are immutable
# TypeError: 'tuple' object does not support item assignment
# my_data[0] = 101
# print(my_data)
Output:
(1, [9, 8, 7], 'World')
(1, [9, 8, 99], 'World')
4.2 Delete operation on tuple
We already discussed above that tuple elements are immutable which also means that we cannot delete the elements of a tuple. However deleting entire tuple is possible.
my_data = (1, 2, 3, 4, 5, 6)
print(my_data)
# not possible
# error
# del my_data[2]
# deleting entire tuple is possible
del my_data
# not possible
# error
# because my_data is deleted
# print(my_data)
Output:
(1, 2, 3, 4, 5, 6)
4.3 Slicing operation in tuples
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)
# elements from 3rd to 5th
# prints (33, 44, 55)
print(my_data[2:5])
# elements from start to 4th
# prints (11, 22, 33, 44)
print(my_data[:4])
# elements from 5th to end
# prints (55, 66, 77, 88, 99)
print(my_data[4:])
# elements from 5th to second last
# prints (55, 66, 77, 88)
print(my_data[4:-1])
# displaying entire tuple
print(my_data[:])
Output:
(11, 22, 33, 44, 55, 66, 77, 88, 99)
(33, 44, 55)
(11, 22, 33, 44)
(55, 66, 77, 88, 99)
(55, 66, 77, 88)
(11, 22, 33, 44, 55, 66, 77, 88, 99)
4.4 Membership Test in Tuples
in: Checks whether an element exists in the specified tuple.
not in: Checks whether an element does not exist in the specified tuple.
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)
# true
print(22 in my_data)
# false
print(2 in my_data)
# false
print(88 not in my_data)
# true
print(101 not in my_data)
Output:
(11, 22, 33, 44, 55, 66, 77, 88, 99)
True
False
False
True
4.5 Iterating a tuple
# tuple of fruits
my_tuple = ("Apple", "Orange", "Grapes", "Banana")
# iterating over tuple elements
for fruit in my_tuple:
print(fruit)
Output:
Apple
Orange
Grapes
Banana
Python Sets
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
Creating a Set
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by ‘comma’.
Note – A set cannot have mutable elements like a list, set or dictionary, as its elements.
# Python program to demonstrate
# Creation of Set in Python
# Creating a Set
set1 = set()
print("Intial blank Set: ")
print(set1)
# Creating a Set with
# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
# Creating a Set with
# the use of Constructor
# (Using object to Store String)
String = 'GeeksForGeeks'
set1 = set(String)
print("\nSet with the use of an Object: " )
print(set1)
# Creating a Set with
# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)
Adding Elements to a Set
Using add() method
Python Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Key value is provided in the dictionary to make it more optimized.
Note – Keys in a dictionary doesn’t allows Polymorphism.
Creating a Dictionary
In Python, a Dictionary can be created by placing sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
Conversion between data types
We can convert between different data types by using different type conversion functions like int(), float(), str(), etc.
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
Conversion to and from string must contain compatible values.
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'
We can even convert one sequence to another.
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
To convert to dictionary, each element must be a pair:
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
Python Input, Output and Import
Python provides numerous built-in functions that are readily available to us at the Python prompt.
Some of the functions like input() and print() are widely used for standard input and output operations respectively. Let us see the output section first.
Python Output Using print() function
We use the print() function to output data to the standard output device (screen). An example of its use is given below.
print('This sentence is output to the screen')
Output
This sentence is output to the screen
Another example is given below:
a = 5
print('The value of a is', a)
Output
The value of a is 5
In the second print() statement, we can notice that space was added between the string and the value of variable a. This is by default, but we can change it.
The actual syntax of the print() function is:
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout (screen). Here is an example to illustrate this.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output
1 2 3 4
1*2*3*4
1#2#3#4&
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print(‘The value of x is {} and y is {}’.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using numbers (tuple index).
print(‘I love {0} and {1}’.format(‘bread’,’butter’))
print(‘I love {1} and {0}’.format(‘bread’,’butter’))
Output
I love bread and butter
I love butter and bread
We can even use keyword arguments to format the string.
>>> print(‘Hello {name}, {greeting}’.format(greeting = ‘Goodmorning’, name = ‘John’))
Hello John, Goodmorning
We can also format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
Python Input
Up until now, our programs were static. The value of variables was defined or hard coded into the source code.
To allow flexibility, we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is:
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.
>>> num = input(‘Enter a number: ‘)
Enter a number: 10
>>> num
’10’
Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
This same operation can be performed using the eval() function. But eval takes it further. It can evaluate even expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5
Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this.
For example, we can import the math module by typing the following line:
import math
We can use the module in the following ways:
import math
print(math.pi)
Output
3.141592653589793
Now all the definitions inside math module are available in our scope. We can also import some specific attributes and functions only, using the from keyword. For example:
>>> from math import pi
>>> pi
3.141592653589793
While importing a module, Python looks at several places defined in sys.path. It is a list of directory locations.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
Python Namespace and Scope
Name (also called identifier) is simply a name given to objects. Everything in Python is an object. Name is a way to access the underlying object.
For example, when we do the assignment a = 2, 2 is an object stored in memory and a is the name we associate it with. We can get the address (in RAM) of some object through the built-in function id(). Let’s look at how to use it.
# Note: You may get different values for the id
a = 2
print('id(2) =', id(2))
print('id(a) =', id(a))
Output
id(2) = 9302208
id(a) = 9302208
Here, both refer to the same object 2, so they have the same id(). Let’s make things a little more interesting.
# Note: You may get different values for the id
a = 2
print('id(a) =', id(a))
a = a+1
print('id(a) =', id(a))
print('id(3) =', id(3))
b = 2
print('id(b) =', id(b))
print('id(2) =', id(2))
Output
id(a) = 9302208
id(a) = 9302240
id(3) = 9302240
id(b) = 9302208
id(2) = 9302208
What is happening in the above sequence of steps? Let’s use a diagram to explain this:
Memory diagram of variables in Python
Initially, an object 2 is created and the name a is associated with it, when we do a = a+1, a new object 3 is created and now a is associated with this object.
Note that id(a) and id(3) have the same values.
Furthermore, when b = 2 is executed, the new name b gets associated with the previous object 2.
This is efficient as Python does not have to create a new duplicate object. This dynamic nature of name binding makes Python powerful; a name could refer to any type of object.
>>> a = 5
>>> a = 'Hello World!'
>>> a = [1,2,3]
All these are valid and a will refer to three different types of objects in different instances. Functions are objects too, so a name can refer to them as well.
def printHello():
print("Hello")
a = printHello
a()
Output
Hello
The same name a can refer to a function and we can call the function using this name
What is a Namespace in Python?
Now that we understand what names are, we can move on to the concept of namespaces.
To simply put it, a namespace is a collection of names.
In Python, you can imagine a namespace as a mapping of every name you have defined to corresponding objects.
Different namespaces can co-exist at a given time but are completely isolated.
A namespace containing all the built-in names is created when we start the Python interpreter and exists as long as the interpreter runs.
This is the reason that built-in functions like id(), print() etc. are always available to us from any part of the program. Each module creates its own global namespace.
These different namespaces are isolated. Hence, the same name that may exist in different modules do not collide.
Modules can have various functions and classes. A local namespace is created when a function is called, which has all the names defined in it. Similar, is the case with class. Following diagram may help to clarify this concept.
A diagram of different namespaces in Python
f-strings in Python 3 – Formatted string literals
new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings
To create an f-string, prefix the string with the letter “ f ”.
# Python3 program introducing f-string
val = 'Geeks'
print(f"{val}for{val} is a portal for {val}.")
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")
Enumerate() in Python
A lot of times when dealing with iterators, we also get a need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task.
Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.
Syntax:
enumerate(iterable, start=0)
Parameters:
Iterable: any object that supports iteration
Start: the index value from which the counter is
to be started, by default it is 0
# Python program to illustrate
# enumerate function
l1 = ["eat","sleep","repeat"]
s1 = "geek"
# creating enumerate objects
obj1 = enumerate(l1)
obj2 = enumerate(s1)
print "Return type:",type(obj1)
print list(enumerate(l1))
# changing start index to 2 from 0
print list(enumerate(s1,2))
Output:
Return type: < type ‘enumerate’ >
[(0, ‘eat’), (1, ‘sleep’), (2, ‘repeat’)]
[(2, ‘g’), (3, ‘e’), (4, ‘e’), (5, ‘k’)]
# Python program to illustrate
# enumerate function in loops
l1 = ["eat","sleep","repeat"]
# printing the tuples in object directly
for ele in enumerate(l1):
print ele
print
# changing index and printing separately
for count,ele in enumerate(l1,100):
print count,ele
Output:
(0, ‘eat’)
(1, ‘sleep’)
(2, ‘repeat’)
100 eat
101 sleep
102 repeat
__name__ (A Special variable) in Python
- Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed.
- However, before doing that, it will define a few special variables. __name__ is one such special variable.
- If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__”.
- If this file is being imported from another module, __name__ will be set to the module’s name.
- __name__ is a built-in variable which evaluates to the name of the current module.
- Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement,
eg:
print "File1 __name__ = %s" %__name__
if __name__ == "__main__":
print "File1 is being run directly"
else:
print "File1 is being imported"
import File1
print "File2 __name__ = %s" %__name__
if __name__ == "__main__":
print "File2 is being run directly"
else:
print "File2 is being imported"
join() function in Python
The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.
Syntax:
string_name.join(iterable)
string_name: It is the name of string in which
joined elements of iterable will be
stored.
Parameters: The join() method takes iterable – objects capable of returning its members one at a time. Some examples are List, Tuple, String, Dictionary and Set
Return Value: The join() method returns a string concatenated with the elements of iterable.
Type Error: If the iterable contains any non-string values, it raises a TypeError exception.
# Python program to demonstrate the
# use of join function to join list
# elements with a character.
list1 = ['1','2','3','4']
# joins elements of list1 by '-'
# and stores in sting s
s = “-”.join(list1)
# join use to join a list of
# strings to a separator s
print(s)
Output:
1-2-3-4