Variable Function: Python Keywords and Identifiers
Variable Function: Python Keywords and Identifiers
com)
Python Keywords
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.
There are 33 keywords in Python 3.7. This number can vary slightly over the course of time.
All the keywords except True, False and None are in lowercase and they must be written as they are. The list
of all the keywords is given below.
False await else import pass
asser
del global not with
t
asyn
elif if or yield
c
Looking at all the keywords at once and trying to figure out what they mean might be overwhelming.
If you want to have an overview, here is the complete list of all the keywords with examples.
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
1. 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.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
3. Keywords cannot be used as identifiers.
global = 1
Output
File "<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@ = 0
Output
File "<interactive input>", line 1 a@ = 0
^
SyntaxError: invalid syntax
5. An identifier can be of any length.
Things to Remember
Python is a case-sensitive language. This means, Variable and variable are not the same.
Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count = 10 would
make more sense, and it would be easier to figure out what it represents when you look at your code after a
long gap.
Multiple words can be separated using an underscore, like this_is_a_long_variable.
Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an assignment
statement. if statement, for statement, while statement, etc. are other kinds of statements which will be
discussed later.
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.
Incorrect indentation will result in IndentationError.
Python Comments
Comments are very important while writing a program. They describe what is going on inside a program, so
that a person looking at the source code does not have a hard time figuring it out.
You might forget the key details of the program you just wrote in a month's time. So taking the time to
explain these concepts in the form of comments is always fruitful.
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers to better understand a program.
Python Interpreter ignores comments.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
We can have comments that extend up to multiple lines. One way is to use the hash(#) symbol at the
beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as a multi-line comment as
well. Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
To learn more about comments, visit Python Comments.
Docstrings in Python
A docstring is short for documentation string.
Python docstrings (documentation strings) are the string literals that appear right after the definition of a
function, method, class, or module.
Triple quotes are used while writing docstrings. For example:
def double(num):
"""Function to double the value"""
return 2*num
Docstrings appear right after the definition of a function, class, or a module. This separates docstrings from
multiline comments using triple quotes.
The docstrings are associated with the object as their __doc__ attribute.
So, we can access the docstrings of the above function with the following lines of code:
def double(num):
"""Function to double the value"""
return 2*num
print(double.__doc__)
Output
Function to double the value
To learn more about docstrings in Python, visit Python Docstrings.
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables as a
container that holds data that can be changed later in the program. For example,
number = 10
Here, we have created a variable named number. We have assigned the value 10 to the variable.
You can think of variables as a bag to store books in it and that book can be replaced at any time.
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.
Note: In Python, we don't actually assign values to the variables. Instead, Python gives the reference of the
object(value) to the variable.
Assigning values to Variables in Python
As you can see from the above example, you can use the assignment operator = to assign a value to a
variable.
Example 1: Declaring and assigning value to a variable
website = "apple.com"
print(website)
Output
apple.com
In the above program, we assigned a value apple.com to the variable website. Then, we printed out
the value assigned to website i.e. apple.com
Note: Python is a type-inferred language, so you don't have to explicitly define the variable type. It
automatically knows that apple.com is a string and declares the website variable as a string.
print(website)
Output
apple.com
programiz.com
In the above program, we have assigned apple.com to the website variable initially. Then, the value
is changed to programiz.com.
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as
containers that hold information which cannot be changed later.
You can think of constants as a bag to store some books which cannot be replaced once placed inside the
bag.
Literals
Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as
follows:
Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical
types: Integer, Float, and Complex.
Example 4: How to use Numeric literals in Python?
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
#Complex Literal
x = 3.14j
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
Output
10 100 200 300
10.5 150.0
3.14j 3.14 0.0
In the above program,
We assigned integer literals into different variables. Here, a is binary literal, b is a decimal literal, c is
an octal literal and d is a hexadecimal literal.
When we print the variables, all the literals are converted into decimal values.
10.5 and 1.5e2 are floating-point literals. 1.5e2 is expressed with exponential and is equivalent to 1.5
* 102.
We assigned a complex literal i.e 3.14j in variable x. Then we use imaginary literal (x.imag)
and real literal (x.real) to create imaginary and real parts of complex numbers.
To learn more about Numeric Literals, refer to Python Numbers.
String literals
A string literal is a sequence of characters surrounded by quotes. We can use both single, double, or
triple quotes for a string. And, a character literal is a single character surrounded by single or double quotes.
Example 7: How to use string literals in Python?
strings = "This is Python"
char = "C"
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"\u00dcnic\u00f6de"
raw_str = r"raw \n string"
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)
Output
This is Python
C
This is a multiline string with more than one line code.
Ünicöde
raw \n string
In the above program, This is Python is a string literal and C is a character literal.
The value in triple-quotes """ assigned to the multiline_str is a multi-line string literal.
The string u"\u00dcnic\u00f6de" is a Unicode literal which supports characters other than English. In this
case, \u00dc represents Ü and \u00f6 represents ö.
r"raw \n string" is a raw string literal.
Boolean literals
A Boolean literal can have any of the two values: True or False.
Example 8: How to use boolean literals in Python?
x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)
Output
x is True y is False a: 5 b: 10
In the above program, we use boolean literal True and False. In Python, True represents the value
as 1 and False as 0. The value of x is True because 1 is equal to True. And, the value
of y is False because 1 is not equal to False.
Similarly, we can use the True and False in numeric expressions as the value. The value of a is 5 because we
add True which has a value of 1 with 4. Similarly, b is 10 because we add the False having value
of 0 with 10.
Special literals
Python contains one special literal i.e. None. We use it to specify that the field has not been created.
Example 9: How to use special literals in Python?
drink = "Available"
food = None
def menu(x):
if x == drink:
print(drink)
else:
print(food)
menu(drink)
menu(food)
Output
Available
None
In the above program, we define a menu function. Inside menu, when we set the argument as drink then, it
displays Available. And, when the argument is food, it displays None.
Literal Collections
There are four different literal collections List literals, Tuple literals, Dict literals, and Set literals.
Example 10: How to use literals collections in Python?
fruits = ["apple", "mango", "orange"] #list
numbers = (1, 2, 3) #tuple
alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary
vowels = {'a', 'e', 'i' , 'o', 'u'} #set
Python Numbers
Integers, floating point numbers and complex numbers fall under Python numbers category. They are
defined as int, float and complex classes in Python.
We can use the type() function to know which class a variable or a value belongs to. Similarly,
the isinstance() function is used to check if an object belongs to a particular class.
a = 5 print(a, "is of type", type(a))
a = 2.0 print(a, "is of type", type(a))
a = 1+2j print(a, "is complex number?", isinstance(1+2j,complex))
Output: 5 is of type <class 'int'> 2.0 is of type <class 'float'> (1+2j) is complex number? True
Integers can be of any length, it is only limited by the memory available.
A floating-point number is accurate up to 15 decimal places. Integer and floating points are separated by
decimal points. 1 is an integer, 1.0 is a floating-point number.
Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part. Here
are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Notice that the float variable b got truncated.
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All
the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ].
a = [1, 2.2, 'python']
We can use the slicing operator [ ] to extract an item or a range of items from a list. The index starts from 0
in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
Python Tuple
Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable.
Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.
It is defined within parentheses () where items are separated by commas.
t = (5,'program', 1+3j)
We can use the slicing operator [] to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# Generates error
# Tuples are immutable
t[0] = 10
Output
t[1] = program
t[0:3] = (5, 'program', (1+3j))
Traceback (most recent call last):
File "test.py", line 11, in <module>
t[0] = 10
TypeError: 'tuple' object does not support item assignment
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings.
Multi-line strings can be denoted using triple quotes, ''' or """.
s = "This is a string" print(s)
s = '''A multiline
string''' print(s)
Output
This is a string A multiline string
Just like a list and tuple, the slicing operator [ ] can be used with strings. Strings, however, are
immutable.
s = 'Hello world!'
# Generates error
# Strings are immutable in Python
s[5] ='d'
Output
s[4] = o s[6:11] = world
Traceback (most recent call last):
File "<string>", line 11, in <module>
TypeError: 'str' object does not support item assignment
Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma inside
braces { }. Items in a set are not ordered.
a = {5,2,3,1,4}
print("a = ", a) # printing set variable
print(type(a)) # data type of variable a
Output
a = {1, 2, 3, 4, 5}
<class 'set'>
We can perform set operations like union, intersection on two sets. Sets have unique values. They eliminate
duplicates.
a = {1,2,2,3,3,3} print(a)
Output
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence, the slicing operator [] does not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing
Python Dictionary
Dictionary is an unordered collection of key-value pairs.
It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We
must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key
and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1]);
print("d['key'] = ", d['key']);
# Generates error
print("d[2] = ", d[2]);
Output
<class 'dict'>
d[1] = value
d['key'] = 2
Traceback (most recent call last):
File "<string>", line 9, in <module>
KeyError: 2
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another data type is
called type conversion. Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
When we run the above program, the output will be:
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Now, let's try adding a string and an integer, and see how Python deals with it.
Example 2: Addition of string(higher) data type and integer(lower) datatype
num_int = 123
num_str = "456"
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
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.
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']
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication,
etc.
Operato
Meaning Example
r
/ Divide left operand by the right one (always results into float) x/y
x % y (remainder o
% Modulus - remainder of the division of left operand by the right
x/y)
Floor division - division that results into whole number adjusted to the
// x // y
left in the number line
> 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
>= 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
Logical operators
Logical operators are the and, or, not operators.
Operator Meaning Example
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
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.
Operato
Meaning Example
r
is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the same
is not x is not True
object)
Example 4: Identity operators in Python
x1 = 5 y1 = 5 x2 = 'Hello' y2 = 'Hello' x3 = [1,2,3] y3 = [1,2,3]
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
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.
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:
a = 10
Here, the variable a is in the global namespace. Variable b is in the local namespace
of outer_function() and c is in the nested local namespace of inner_function().
When we are in inner_function(), c is local to us, b is nonlocal and a is global. We can read as well as assign
new values to c but can only read b and a from inner_function().
If we try to assign as a value to b, a new variable b is created in the local namespace which is different than
the nonlocal b. The same thing happens when we assign a value to a.
However, if we declare a as global, all the reference and assignment go to the global a. Similarly, if we want
to rebind the variable b, it must be declared as nonlocal. The following example will further clarify this.
def outer_function():
a = 20
def inner_function():
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
outer_function()
print('a =', a)
As you can see, the output of this program is
a = 30 a = 20 a = 10
In this program, three different variables a are defined in separate namespaces and accessed accordingly.
While in the following program,
def outer_function():
global a
a = 20
def inner_function():
global a
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
outer_function()
print('a =', a)
The output of the program is.
a = 30 a = 30 a = 30
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
When you run the program, the output will be:
3 is a positive number
This is always printed
This is also always printed.
In the above example, num > 0 is the test expression.
The body of if is executed only if this evaluates to True.
When the variable num is equal to 3, test expression is true and statements inside the body of if are executed.
If the variable num is equal to -1, test expression is false and statements inside the body of if are skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test
expression.
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output
Positive or Zero
In the above example, when num is equal to 3, the test expression is true and the body of if is executed and
the body of else is skipped.
If num is equal to -5, the test expression is false and the body of else is executed and the body of if is
skipped.
If num is equal to 0, the test expression is true and body of if is executed and body of else is skipped.
Example of if...elif...else
'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.
Python Nested if statements
We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in
computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out
the level of nesting. They can get confusing, so they must be avoided unless necessary.
Python Nested if Example
'''In this program, we input a number
check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
for i in digits:
print(i)
else:
print("No items left.")
When you run the program, the output will be:
0 1 5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the
block of code in the else and prints No items left.
This for...else statement can be used with the break keyword to run the else block only when
the break keyword was not executed. Let's take an example:
# program to display student's marks from record
student_name = 'Soyuj'
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
counter = 0
print("The end")
Output
S t r
The end
In this program, we iterate through the "string" sequence. We check if the letter is i, upon which we break
from the loop. Hence, we see in our output that all the letters up till i gets printed. After that, the loop
terminates.
The working of continue statement in for and while loop is shown below.
print("The end")
Output
s t r n g
The end
This program is same as the above example except the break statement has been replaced with continue.
We continue with the loop, if the string is i, not executing the rest of the block. Hence, we see in our output
that all the letters except i gets printed.
greet('Paul')
Docstrings
The first string after the function header is called the docstring and is short for documentation string. It is
briefly used to explain what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what you had
for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally use triple
quotes so that docstring can extend up to multiple lines. This string is available to us as the __doc__ attribute
of the function.
For example:
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Output
2 4
x = 20
my_func()
print("Value outside function:",x)
Output
Value inside function: 10 Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the function my_func() changed the value
of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the one outside.
Although they have the same names, they are two different variables with different scopes.
On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. In order to modify the
value of variables outside the function, they must be declared as global variables using the keyword global.
Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
Functions Arguments
In the user-defined function topic, we learned about defining a function and calling it. Otherwise, the
function call will result in an error. Here is an example.
def greet(name, msg):
"""This function greets to
the person with the provided message"""
print("Hello", name + ', ' + msg)
greet("Kate")
greet("Bruce", "How do you do?")
Output
Hello Kate, Good morning!
Hello Bruce, How do you do?
In this function, the parameter name does not have a default value and is required (mandatory) during a call.
On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional during a
call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a default argument, all
the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if we had defined
the function header above as:
def greet(msg = "Good morning!", name):
We would get an error as:
SyntaxError: non-default argument follows default argument
What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other. Any object in between
them would be reflected recursively.
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output
The factorial of 3 is 6
In the above example, factorial() is a recursive function as it calls itself.
When we call this function with a positive integer, it will recursively call itself by decreasing the number.
Each function multiplies the number with the factorial of the number below it until it is equal to one. This
recursive call can be explained in the following steps.
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
Let's look at an image that shows a step-by-step process of what is going on:
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the function calls itself
infinitely.
The Python interpreter limits the depths of recursion to help avoid infinite recursions, resulting in stack
overflows.
By default, the maximum depth of recursion is 1000. If the limit is crossed, it results in RecursionError.
Let's look at one such condition.
def recursor():
recursor()
recursor()
Output
Traceback (most recent call last):
File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
print(double(5))
Output
10
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the
expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier double. We can
now call it as a normal function. The statement
double = lambda x: x * 2
is nearly the same as:
def double(x):
return x * 2
print(new_list)
Output
[4, 6, 8, 12]
Example use with map()
The map() function in Python takes in a function and a list.
The function is called with all the items in the list and a new list is returned which contains items returned
by that function for each item.
Here is an example use of map() function to double all the items in a list.
# Program to double each item in a list using map()
print(new_list)
Output
[2, 10, 8, 12, 16, 22, 6, 24]
Global Variables
In Python, a variable declared outside of the function or in global scope is known as a global variable. This
means that a global variable can be accessed inside or outside of the function.
Let's see an example of how a global variable is created in Python.
Example 1: Create a Global Variable
x = "global"
def foo():
print("x inside:", x)
foo()
print("x outside:", x)
Output
x inside: global
x outside: global
In the above code, we created x as a global variable and defined a foo() to print the global variable x.
Finally, we call the foo() which will print the value of x.
What if you want to change the value of x inside a function?
x = "global"
def foo():
x=x*2
print(x)
foo()
Output
UnboundLocalError: local variable 'x' referenced before assignment
The output shows an error because Python treats x as a local variable and x is also not defined inside foo().
To make this work, we use the global keyword. Visit Python Global Keyword to learn more.
Local Variables
A variable declared inside the function's body or in the local scope is known as a local variable.
Example 2: Accessing local variable outside the scope
def foo():
y = "local"
foo()
print(y)
Output
NameError: name 'y' is not defined
The output shows an error because we are trying to access a local variable y in a global scope whereas the
local variable only works inside foo() or local scope.
def foo():
global x
y = "local"
x=x*2
print(x)
print(y)
foo()
Output
global global
local
In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use multiplication
operator * to modify the global variable x and we print both x and y.
After calling the foo(), the value of x becomes global global because we used the x * 2 to print two
times global. After that, we print the value of local variable y i.e local.
Nonlocal Variables
Nonlocal variables are used in nested functions whose local scope is not defined. This means that the
variable can be neither in the local nor the global scope.
Let's see an example of how a nonlocal variable is used in Python.
We use nonlocal keywords to create nonlocal variables.
Example 6: Create a nonlocal variable
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
Output
inner: nonlocal
outer: nonlocal
In the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal
variable. The inner() function is defined in the scope of another function outer().
Note : If we change the value of a nonlocal variable, the changes appear in the local variable.
add()
When we run the above program, the output shows an error:
UnboundLocalError: local variable 'c' referenced before assignment
This is because we can only access the global variable but cannot modify it from inside the function.
The solution for this is to use the global keyword.
def add():
global c
c = c + 2 # increment by 2
print("Inside add():", c)
add()
print("In main:", c)
When we run the above program, the output will be:
Inside add(): 2
In main: 2
In the above program, we define c as a global keyword inside the add() function.
Then, we increment the variable c by 1, i.e c = c + 2. After that, we call the add() function. Finally, we print
the global variable c.
As we can see, change also occurred on the global variable outside the function, c = 2.
config.a = 10
config.b = "alphabet"
Create a main.py file, to test changes in value
import config
import update
print(config.a)
print(config.b)
When we run the main.py file, the output will be
10
alphabet
In the above, we have created three files: config.py, update.py, and main.py.
The module config.py stores global variables of a and b. In the update.py file, we import
the config.py module and modify the values of a and b. Similarly, in the main.py file, we import
both config.py and update.py module. Finally, we print and test the values of global variables whether they
are changed or not.
import math
print("The value of pi is", math.pi)
When you run the program, the output will be:
The value of pi is 3.141592653589793
import math as m
print("The value of pi is", m.pi)
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is the correct
implementation.
Reloading a module
The Python interpreter imports a module only once during a session. This makes things more efficient. Here
is an example to show how this works.
Suppose we have the following code in a module named my_module.
# This module shows the effect of
# multiple imports and reload
# Output: 13
print(0o15)
When you run the program, the output will be:
107 253 13
Type Conversion
We can convert one type of number into another. This is also known as coercion.
Operations like addition, subtraction coerce integer to float implicitly (automatically), if one of the operands
is float.
>>> 1 + 2.0 3.0
We can see above that 1 (integer) is coerced into 1.0 (float) for addition and the result is also a floating point
number.
We can also use built-in functions like int(), float() and complex() to convert between types explicitly. These
functions can even convert from strings.
>>> int(2.3) 2
>>> int(-2.8) -2
>>> float(5) 5.0
>>> complex('3+5j') (3+5j)
When converting from float to integer, the number gets truncated (decimal parts are removed).
Python Decimal
Python built-in class float performs some calculations that might amaze us. We all know that the sum of 1.1
and 2.2 is 3.3, but Python seems to disagree.
>>> (1.1 + 2.2) == 3.3
False
What is going on?
It turns out that floating-point numbers are implemented in computer hardware as binary fractions as the
computer only understands binary (0 and 1). Due to this reason, most of the decimal fractions we know,
cannot be accurately stored in our computer.
Let's take an example. We cannot represent the fraction 1/3 as a decimal number. This will give
0.33333333... which is infinitely long, and we can only approximate it.
It turns out that the decimal fraction 0.1 will result in an infinitely long binary fraction of
0.000110011001100110011... and our computer only stores a finite number of it.
This will only approximate 0.1 but never be equal. Hence, it is the limitation of our computer hardware and
not an error in Python.
>>> 1.1 + 2.2
3.3000000000000003
To overcome this issue, we can use the decimal module that comes with Python. While floating-point
numbers have precision up to 15 decimal places, the decimal module has user-settable precision.
Let's see the difference:
import decimal
print(0.1)
print(decimal.Decimal(0.1))
Output:
0.1 0.1000000000000000055511151231257827021181583404541015625
This module is used when we want to carry out decimal calculations as we learned in school.
It also preserves significance. We know 25.50 kg is more accurate than 25.5 kg as it has two significant
decimal places compared to one.
from decimal import Decimal as D
print(D('1.1') + D('2.2'))
print(D('1.2') * D('2.50'))
Output : 3.3 3.000
Notice the trailing zeroes in the above example.
We might ask, why not implement Decimal every time, instead of float? The main reason is efficiency.
Floating point operations are carried out must faster than Decimal operations.
When to use Decimal instead of float?
We generally use Decimal in the following cases.
When we are making financial applications that need exact decimal representation.
When we want to control the level of precision required.
When we want to implement the notion of significant decimal places.
Python Fractions
Python provides operations involving fractional numbers through its fractions module.
A fraction has a numerator and a denominator, both of which are integers. This module has support for
rational number arithmetic.
We can create Fraction objects in various ways. Let's have a look at them.
import fractions
print(fractions.Fraction(1.5))
print(fractions.Fraction(5))
print(fractions.Fraction(1,3))
Output: 3/2 5 1/3
While creating Fraction from float, we might get some unusual results. This is due to the imperfect binary
floating point number representation as discussed in the previous section.
Fortunately, Fraction allows us to instantiate with string as well. This is the preferred option when using
decimal numbers.
import fractions
# As float
# Output: 2476979795053773/2251799813685248
print(fractions.Fraction(1.1))
# As string
# Output: 11/10
print(fractions.Fraction('1.1'))
Output
2476979795053773/2251799813685248
11/10
This data type supports all basic operations. Here are a few examples.
from fractions import Fraction as F
print(F(1, 3) + F(1, 3))
print(1 / F(5, 6))
print(F(-3, 10) > 0)
print(F(-3, 10) < 0)
Output: 2/3 6/5 False True
Python Mathematics
Python offers modules like math and random to carry out different mathematics like trigonometry,
logarithms, probability and statistics, etc.
import math
print(math.pi)
print(math.cos(math.pi))
print(math.exp(10))
print(math.log10(1000))
print(math.sinh(1))
print(math.factorial(6))
Output:
3.141592653589793
-1.0
22026.465794806718
3.0
1.1752011936438014
720
Here is the full list of functions and attributes available in the Python math module.
import random
print(random.randrange(10, 20))
x = ['a', 'b', 'c', 'd', 'e']
# Get random choice
print(random.choice(x))
# Shuffle x
random.shuffle(x)
Python offers a range of compound data types often referred to as sequences. List is one of the most
frequently used and very versatile data types used in Python.
# list of integers
my_list = [1, 2, 3]
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1])
print(n_list[1][3])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second
last item and so on.
# Negative indexing in lists
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])
When we run the above program, we will get the following output:
e
p
my_list = ['p','r','o','g','r','a','m','i','z']
print(odd)
print(odd)
Output
[1, 4, 6, 8]
[1, 3, 5, 7]
We can add one item to a list using the append() method or add several items using extend() method.
# Appending and Extending lists in Python
odd = [1, 3, 5]
odd.append(7)
print(odd)
print(odd)
Output
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]
We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.
# Concatenating and repeating lists
odd = [1, 3, 5]
print(["re"] * 3)
Output
[1, 3, 5, 9, 7, 5]
['re', 're', 're']
Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple
items by squeezing it into an empty slice of a list.
# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)
print(odd)
odd[2:2] = [5, 7]
print(odd)
Output
[1, 3, 9]
[1, 3, 5, 7, 9]
print(my_list)
print(my_list)
# Output: 'o'
print(my_list.pop(1))
my_list.clear()
# Output: []
print(my_list)
Output
['r', 'o', 'b', 'l', 'e', 'm']
o
['r', 'b', 'l', 'e', 'm']
m
['r', 'b', 'l', 'e']
[]
Finally, we can also delete items in a list by assigning an empty list to a slice of elements.
>>> my_list = ['p','r','o','b','l','e','m']
>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']
# Output: 1
print(my_list.index(8))
# Output: 2
print(my_list.count(8))
my_list.sort()
# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)
my_list.reverse()
# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)
Output
1
2
[0, 1, 3, 4, 6, 8, 8]
[8, 8, 6, 4, 3, 1, 0]
# Output: False
print('a' in my_list)
# Output: True
print('c' not in my_list)
Output: True False True
A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements
of a tuple once it is assigned whereas we can change the elements of a list.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. The
parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output: () (1, 2, 3) (1, 'Hello', 3.4) ('mouse', [8, 4, 6], (1, 2, 3))
A tuple can also be created without using parentheses. This is known as tuple packing.
my_tuple = 3, 4.6, "dog"
print(my_tuple)
print(a) #3
print(b) # 4.6
print(c) # dog
Output:(3, 4.6, 'dog') 3 4.6 dog
Creating a tuple with one element is a bit tricky.
Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is, in
fact, a tuple.
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
Output: <class 'str'> <class 'tuple'> <class 'tuple'>
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
Output: p t s 4
2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Output: t p
3. Slicing
We can access a range of items in a tuple by using the slicing operator colon :.
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','z')
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once they have been assigned. But, if the element is
itself a mutable data type like list, its nested items can be changed.
We can also assign a tuple to different values (reassignment).
# Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
Output: (4, 2, 3, [9, 5]) ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
We can use + operator to combine two tuples. This is called concatenation.
We can also repeat the elements in a tuple for a given number of times using the * operator.
Both + and * operations result in a new tuple.
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Output: (1, 2, 3, 4, 5, 6) ('Repeat', 'Repeat', 'Repeat')
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove
items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.
# Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two methods are
available.
Some examples of Python tuple methods:
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3
Output : 2 3
# In operation
print('a' in my_tuple)
print('b' in my_tuple)
# Not in operation
print('g' not in my_tuple)
Output: True False True
2. Iterating Through a Tuple
We can use a for loop to iterate through each item in a tuple.
# Using a for loop to iterate through a tuple
for name in ('John', 'Kate'):
print("Hello", name)
Output: Hello John Hello Kate
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
When we run the above program, we get the following output:
str1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
Writing two string literals together also concatenates them like + operator.
If we want to concatenate strings in different lines, we can use parentheses.
>>> # two string literals together
>>> 'Hello ''World!'
'Hello World!'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
When we run the above program, we get the following output:
list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]
len(str) = 4
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
Set
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable
(cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference,
etc.
# initialize a with {}
a = {}
# my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
Output: {1, 3, 4, 5, 6} {1, 3, 5, 6} {1, 3, 5} {1, 3, 5}
Traceback (most recent call last):
File "<string>", line 28, in <module>
KeyError: 2
Similarly, we can remove and return an item using the pop() method.
Since set is an unordered data type, there is no way of determining which item will be popped. It is
completely arbitrary.
We can also remove all the items from a set using the clear() method.
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
print(my_set)
Output: {'H', 'l', 'r', 'W', 'o', 'd', 'e'} H {'r', 'W', 'o', 'd', 'e'} set()
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
Output: {1, 2, 3, 4, 5, 6, 7, 8}
Try the following examples on Python shell.
# use union function
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
Set Intersection
Intersection of A and B is a set of elements that are common in both the sets.
Intersection is performed using & operator. Same can be accomplished using the intersection() method.
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
Output: {4, 5}
Try the following examples on Python shell.
# use intersection function on A
>>> A.intersection(B)
{4, 5}
Set Difference
Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using the difference() method.
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
Output: {1, 2, 3}
Try the following examples on Python shell.
# use difference function on A
>>> A.difference(B)
{1, 2, 3}
# use - operator on B
>>> B - A
{8, 6, 7}
Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the
intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference().
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Output: {1, 2, 3, 6, 7, 8}
Try the following examples on Python shell.
# use symmetric_difference function on A
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
intersection_update() Updates the set with the intersection of itself and another
symmetric_difference_up
Updates a set with the symmetric difference of itself and another
date()
update() Updates the set with the union of itself and others
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
Returns an enumerate object. It contains the index and value for all the items of the
enumerate()
set as a pair.
len() Returns the length (the number of items) in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once
assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets
are hashable and can be used as keys to a dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods
like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and unio
n(). Being immutable, it does not have methods that add or remove elements.
# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
Try these examples on Python shell.
>>> A.isdisjoint(B)
False
>>> A.difference(B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> A.add(3)
...
AttributeError: 'frozenset' object has no attribute 'add'
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
As you can see from above, we can also create a dictionary using the built-in dict() function.
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# KeyError
print(my_dict['address'])
Output: Jack 26 None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares) # Output: {}
fromkeys(seq[,
Returns a new dictionary with keys from seq and value equal to v (defaults to None).
v])
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
Removes and returns an arbitrary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.
setdefault(key[ Returns the corresponding value if the key is in the dictionary. If not, inserts the key
,d]) with a value of d and returns d (defaults to None).
Updates the dictionary with the key/value pairs from other, overwriting existing
update([other])
keys.
print(squares)
Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
A dictionary comprehension can optionally contain more for or if statements.
An optional if statement can filter out items to form the new dictionary.
Here are some examples to make a dictionary with only odd items.
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)
Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
To learn more dictionary comprehensions, visit Python Dictionary Comprehension.
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.