Pychapt2 New
Pychapt2 New
, Basmath
Unit-II
Data Types, Variables, Expressions, Statements and
Control Structures
Employing Variables:-
Variable:-
In most of the programming languages a variable is a named location used to store data in
the memory. Each variable must have a unique name called identifier. It is helpful to think
of variables as container that holds data which can be changed later throughout
programming
In Python, variables do not need declaration to reserve memory space. The "variable
declaration" or "variable initialization" happens automatically when we assign a value to a
variable.
You can use the assignment operator = to assign the value to a variable.
print(website)
In the above program, we assigned a value Apple.com to the variable website. Then we print
the value assigned to website i.e Apple.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.
Non technically, you can think of constant as a bag to store some books and those books
cannot be replaced once placed inside the bag.
In Python, constants are usually declared and assigned on a module. Here, the module
means a new file containing variables, functions etc which is imported to main file. Inside the
module, constants are written in all capital letters and underscores separating the words.
Create a constant.py
PI = 3.14
GRAVITY = 9.8
Create a main.py
import constant
print(constant.PI)
print(constant.GRAVITY)
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant
value to PI and GRAVITY. After that, we create a main.py file and import the constant
module. Finally, we print the constant value.
Note: In reality, we don't use constants in Python. The globals or constants module is used
throughout the Python programs.
1. Create a name that makes sense. Suppose, vowel makes more sense than v.
2. Use camelCase notation to declare a variable. It starts with lowercase letter. For
example:
3. myName
4. myAge;
myAddress
Numeric:-
Python supports the usual numeric types (integer, long integer, floating and complex
numbers). Programming support, including a complex number type, an unlimited precision
integer.
Examples of integers include 4, −19, 0, and −1005. Integers can be of any length, it is only
limited by the memory available.
Long integers:-
Now for something more exotic: here's a look at long integers in action. When an integer
constant ends with an L (or lowercase l), Python creates a long integer, which can be
arbitrarily big:
>>> 9999999999999999999999999999 + 1
Overflow Error: integer literal too large
>>> 9999999999999999999999999999L + 1
10000000000000000000000000000L
Complex numbers:-
Python complex constants are written as real-part + imaginary-part, and terminated with a j
or J. Internally, they are implemented as a pair of floating-point numbers, but all numeric
operations perform complex math when applied to complex numbers.
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.
>>> c = 1+2j
>>> c
(1+2j)
Strings:-
String an ordered collection of characters, used to store and represent text-based
information. From a functional perspective, strings can be used to represent just about
anything that can be encoded as text: symbols and words (e.g., your name), contents of text
files loaded into memory, and so on.
We can use single quotes or double quotes to represent strings. Multi-line strings can be
denoted using triple quotes, ''' or """.
Boolean values:-
Finally, we should mention the boolean type. This is a value which is either True or False.
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index
starts form 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
print("a[2] = ", a[2])
>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]
Tuple:-
Tuple is an ordered sequence of items same as 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 list as it cannot change
dynamically.
We can use the slicing operator [] to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# Generates error
# Tuples are immutable
t[0] = 10
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))
2
>>>>d1={‘food’:’spam’,’test’:’ym’}
>>>>d2={1:’Python’,2:’JSP’,3:’c#’}
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}
We can perform set operations like union, intersection on two sets. Set have unique values.
They eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
Prof. Gajendra D. Dhole 5
MIT College of C.S. & I.T., Basmath
Since, set are unordered collection, indexing has no meaning. Hence the slicing operator []
does not work.
>>> a = {1,2,3}
>>> a[1]
Output function:-
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given
below.
In the second print() statement, we can notice that a space was added between the string
and the value of variable a. This is by default, but we can change it.
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 are an example to illustrate this.
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
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 it is
printed by using numbers (tuple index).
We can even 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
Input function:-
Up till now, our programs were static. The value of variables were 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])
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.
This same operation can be performed using the eval() function. But it takes it further. It can
evaluate even expressions, provided the input is a string
>>> int('2+3')
>>> eval('2+3')
5
Correcting Errors:-
When coding programs there are three common types of error that can occur. It is useful to
recognize these different error types in Python programming so they can be corrected more
easily:
Syntax Error – occurs when the interpreter encounters code that does not conform
to the Python language rules. For example, a missing quote mark around a string.
The interpreter halts and reports the error without executing the program.
Runtime Error – occurs during execution of the program, at the time when the
program runs. For example, when a variable name is later mis-typed so the variable
cannot be recognized. The interpreter runs the program but halts at the error and
reports the nature of the error as an “Exception”.
Semantic Error – occurs when the program performs unexpectedly. For example,
when order precedence has not been specified in an expression. The interpreter runs
the program and does not report an error.
Correcting syntax and runtime errors is fairly straightforward, as the interpreter reports where
the error occurred or the nature of the error type, but semantic errors require code
examination.
Programming errors are often called “bugs” and the process of tracking them down is often
called “debugging”.
Step 1
Open an IDLE Edit Window then add a statement to output a string that omits a closing
quote mark
print( ‘Coding for Beginners in easy steps )
Step 2
Save then run the program to see the interpreter highlight the syntax error and indicate its
nature
Step 3
Insert a quote mark before the closing parenthesis to terminate the string and save then run
the program again – to see the error has been corrected
Step 4
Next, begin a new program by initializing a variable then try to output its value with an
incorrect variable name – to see the interpreter report a runtime error
title = ‘Coding for Beginners in easy steps’
print( titel )
Step 5
Amend the variable name to match that in the variable declaration and save then run the
program again – to see the error has been corrected
Step 6
Now, begin a new program by initializing a variable then try to output an expression using its
value without explicit precedence – to see a possibly unexpected result of 28
num = 3
print( ‘Result: ‘ , num * 8 + 4 )
Add parentheses to group the expression as 3 * ( 8 + 4 ) then save the file and run the
program again – to see the expected result of 36, correcting the semantic error
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output
of the operation.
Arithmetic operators:-
Comparing Values:-
Comparison operators:-
Comparison operators are used to compare values. It either returns True or False according
to the condition.
Comparison operators in Python
Prof. Gajendra D. Dhole 10
MIT College of C.S. & I.T., Basmath
Operator Meaning Example
> Greater that - True if left operand is greater than the right x>y
< Less that - 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
>= x >= y
the right
Less than or equal to - True if left operand is less than or equal to the
<= x <= y
right
Assigning Logic:-
Bitwise operators:-
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit,
hence the name.
Assigning Values:-
Assignment operators:-
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.
Special operators:-
Python language offers some special type 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
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.
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than
33, and so we print to screen that "b is greater than a".
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try
this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true,
so we print to screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is
not true, so we go to the else condition and print to screen that "a is greater than b".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if
statement.
Example
If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line:
Example
a = 2
b = 330
print("A") if a > b else print("B")
You can also have multiple else statements on the same line:
Example
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
Example
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.
Example
a = 33
b = 200
if b > a:
pass
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
Setting precedence:-
The following table lists all operators from highest precedence to lowest.
Operator Description
~+- Complement, unary plus and minus (method names for the last
Example
#!/usr/bin/python
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result –
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
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
>>> 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'
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}
Expressions:-
Statements:-
A statement is a unit of code that the Python interpreter can execute. We have seen two
kinds of statements: print and assignment. When you type a statement in interactive mode,
the interpreter executes it and displays the result, if there is one.
A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
Assignment statements:-
An assignment statement in Python has the form variable = expression. This has the
following effect. First the expression on the right hand side is evaluated, then the result is
assigned to the variable. After the assignment, the variable becomes a name for the result.
The variable retains the same value until another value is assigned, in which case the
previous value is lost.
Executing the assignment produces no output; its purpose it to make the association
between the variable and its value.
>>> x = 2+2
>>> print x
4
In the example above, the assignment statement sets x to 4, producing no output.
Python Indentation:-
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python 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 is preferred over tabs. Here is an
example.
for i in range(1,11):
print(i)
if i == 5:
break
Prof. Gajendra D. Dhole 19
MIT College of C.S. & I.T., Basmath
The enforcement of indentation in Python makes the code look neat and clean. This results
into Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always 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 into IndentationError.
Python Comments:-
Comments are very important while writing a program. It describes what's 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
time to explain these concepts in form of comments is always fruitful.
It extends up to the newline character. Comments are for programmers for better
understanding of a program. Python Interpreter ignores comment.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example:
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 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"""
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 in import math.
import math
print(math.pi)
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:
While importing a module, Python looks at several places defined in sys.path. It is a list of
directory locations.
Decision making is required when we want to execute a code only if a certain condition is
satisfied
If Statement Syntax:-
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True. If the text expression is False, the statement(s) is not executed.
Python interprets non-zero values as True. None and 0 are interpreted as False
If Statement Flowchart:-
Example:-
num=5
if num > 0:
5 is a positive number
if...else Statement:-
If variable num is equal to -1, test expression is false and body inside body of if is skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.
Syntax of if...else:-
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only
when test condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the
blocks.
Prof. Gajendra D. Dhole 22
MIT College of C.S. & I.T., Basmath
If..else Flowchart:-
Example:-
num=-5
if num > 0:
else:
-5 is a negative number
if...elif...else Statement:- If num is equal to 0, the test expression is true and body of if is
executed and body of else is skipped.
Syntax of if...elif...else:-
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.
Flowchart of if...elif...else:-
Example:-
num=5
if num > 0:
elif num==0:
else:
Nested if statements:-
if test expression:
Body of if
if test expression:
Body of if
else:
Body of else
else:
Body of else
Example:-
Loops:-
for loop:-
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal
Loop continues until we reach the last item in the sequence. The body of for loop is
separated from the rest of the code using indentation.
Example: -
Sum=0
Sum=sum+val
The sum is 48
We can also define the start, stop and step size as range(start,stop,step size). step size
defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
A for loop can have an optional else block as well. The else part is executed if the items in
the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.
Example:-
digits=[0,1,5]
for i in digits:
print(i)
else:
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.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
sum=0
i=1
while i<=n
sum=sum+i
Enter n: 10
The sum is 55
n the above program, the test expression will be True as long as our counter variable i is
less than or equal to n (10 in our program).
We need to increase the value of counter variable in the body of the loop. This is very
important (and mostly forgotten). Failing to do so will result in an infinite loop (never ending
loop).
Same as that of for loop, we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such case, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.
Example:-
counter =0
Print(“Inside loop”)
counter =counter+1
else:
print(“Inside else”)
Output
Inside loop
Inside loop
Here, we use a counter variable to print the string Inside loop three times.
On the forth iteration, the condition in while becomes False. Hence, the else part is
executed.
You can also use the While loop of Python to traverse through all the elements of the List
variable. The for loop is helpful to get the values within a certain specified range. The list
variable is the variable whose values are comma-separated. All the items are enclosed
within the square brackets ([]). Let’s find out with the examples given below.
1. For Loop Over Python List Variable and Print All Elements
To get only the items and not the square brackets, you have to use the Python for loop.
Inside the for loop, you have to print each item of a variable one by one in each line.
output
Ram
Shyam
10
Bilal
13.2
Feroz
The above example prints each element of the Python list variable line by line. They are
printed here without any square brackets or quotes. The print statement prints the single
element in each line.
elements between the given range. You can print the element in the range whatever you
want.
Below are the different ranges of length to print the elements of the list in Python.
If you want to print all the elements of the list in Python. You have to use the below-given
Check the below Python coding to print your list element as per your requirement.
output
Ram
Shyam
10
Bilal
13.2
Feroz
The above example prints all the elements of the list element in the output. The above output
To print all the elements of the list variable in Python. You have to use the below-given
Add -1 after the len() function of Python to remove the last element from the output. You
will get all the elements of the list element except the last one.
Ram
Shyam
10
Bilal
13.2
The above example prints all the elements except the last one in the Python List variable.
To remove more elements from the output with the List element of Python. You have to
increase the value you have added after the len() function of Python.
You can increase this value to remove the number of elements from the output.
Ram
Shyam
10
Bilal
The above example prints all the elements except the last two list elements.
each element. You have to use the below-given example to print all the items of the list
element.
In a while loop, you have to first initialize the variable to start the while loop. Inside the
while loop, you also have to add the same variable with the increment operator.
myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz'];
x=0;
while x < len(myList):
print(myList[x])
x += 1
output
Ram
Shyam
10
Prof. Gajendra D. Dhole 32
MIT College of C.S. & I.T., Basmath
Bilal
13.2
Feroz
The above example using the while loop and prints all the elements in the output. Each
item of the list element gets printed line by line.
The for-in loop of Python is the same as the foreach loop of PHP. It prints all the elements of
the list variable in the output. Use the below-given example to print each element using the
for-in loop.
myList = ['Ram', 'Shyam', 10, 'Bilal', 13.2, 'Feroz'];
for List in myList:
print(List)
output
Ram
Shyam
10
Bilal
13.2
Feroz
The above example contains the output which prints all the elements line by line.
Syntax of break:-
Python break statement has very simple syntax where we only use break keyword. We
generally check for a condition with if-else blocks and then use break .
break
if condition:
break
while expression:
if if_expression:
break
break keyword in python that often used with loops for and while to modify the flow of loops.
Loops are used to execute a statement again and again until the expression
becomes False or the sequence of elements becomes empty. But what if, we want to
terminate the loop before the expression become False or we reach the end of the
sequence, and that’s the situation when the break comes in-game.
In the following example, while loop is set to print the first 8 items in the tuple. But what
actually happens is, when the count is equal to 4, it triggers if statement and
the break statement inside it is invoked making the flow of program jump out of the loop.
#declaring a tuple
num = (1,2,3,4,5,6,7,8)
count = 0
while (count<9):
print (num[count])
count = count+1
break
Output
1
2
3
4
End of program
i = 0;
while 1:
print(i,” “,end=””),
i=i+1;
if i == 10:
break;
print(“came out of while loop”);
Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
The continue statement is similar to the break statement. During a program’s execution,
when the break statement is encountered within the body of a loop, the remaining
statements within the body of the loop are skipped, and the loop is exited. When a continue
statement is encountered within a loop, the remaining statements within the body are
skipped, but the loop condition is checked to see if the loop should continue or be exited. If
the loop’s condition is still true, the loop is not exited, but the loop’s execution continues at
the top of the loop.
Example:-
1 sum = 0
2 done = False;
3 while not done:
4 val = eval(input("Enter positive integer (999 quits):"))
5 if val < 0:
6 print("Negative value", val, "ignored")
7 continue; # Skip rest of body for this iteration
8 if val != 999:
9 print("Tallying", val)
10 sum += val
11 else:
The continue statement is not used as frequently as the break statement since it is often
easy to transform the code into an equivalent form that does not use continue.
List:-
Python offers a range of compound datatypes often referred to as sequences. List is one of
the most frequently used and very versatile datatype used in Python .
create a list
In Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
There are various ways in which we can access the elements of a list.
List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So, a list
having 5 elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an
integer. We can't use float or other types, this will result into TypeError.
>>>my_list=['p','r','o','b','e']
>>>print(my_list(0))
>>> n_list=["Happy",[2,0,1,5]]
>>> print(n_list[0][1])
a
>>> print(n_list[1][3])
5
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.
>>>my_list=['p','r','o','b','e']
>>>print(my_list[-1])
e
>>>print(my_list[-5])
p
We can access a range of items in a list by using the slicing operator (colon).
>>> my_list=['p','r','o','g','r','a','m','z']
>>> print(my_list[2:5])
['o', 'g', 'r']
>>> print(my_list[:-5])
['p', 'r', 'o']
>>> print(my_list[5:])
['a', 'm', 'z']
>>> print(my_list[:])
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'z']
>>> odd=[2,4,6,8]
>>> odd
[2, 4, 6, 8]
>>> odd[0]=1
>>> odd
[1, 4, 6, 8]
>>> odd[1:4]=[3,5,7]
>>> odd
[1, 3, 5, 7]
>>>
We can add one item to a list using append() method or add several items using extend()
method.
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
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.
odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
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.
>>> odd=[1,9]
>>> odd
[1, 9]
>>> odd.insert(1,3)
>>> odd
[1, 3, 9]
>>> odd[2:2]=[5,7]
>>> odd
[1, 3, 5, 7, 9]
>>>
We can delete one or more items from a list using the keyword del. It can even delete the list
entirely.
>>> my_list=['p','r','o','g','r','a','m','z']
>>> my_list
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'z']
>>> del my_list[2]
>>> my_list
['p', 'r', 'g', 'r', 'a', 'm', 'z']
>>> del my_list[1:5]
>>> my_list
['p', 'm', 'z']
>>> del my_list
>>> my_list
We can use remove() method to remove the given item or pop() method to remove an item
at the given index.
The pop() method removes and returns the last item if index is not provided. This helps us
implement lists as stacks (first in, last out data structure).
>>> my_list=['p','r','o','g','r','a','m','z']
>>> my_list.remove('p')
>>> print(my_list)
['r', 'o', 'g', 'r', 'a', 'm', 'z']
>>> print(my_list.pop(1))
o
>>> print(my_list)
['r', 'g', 'r', 'a', 'm', 'z']
>>> print(my_list.pop())
z
>>> print(my_list)
['r', 'g', 'r', 'a', 'm']
Finally, we can also delete items in a list by assigning an empty list to a slice of elements.
Methods that are available with list object in Python programming are tabulated below.
They are accessed as list.method(). Some of the methods have already been used above.
Dictionary:-
Python dictionary is an unordered collection of items. While other compound data types have
only value as an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
While values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
As you can see above, we can also create a dictionary using the built-in function dict()
While indexing is used with other container types to access values, dictionary uses keys.
Key can be used either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if the key is not
found.
. >>> my_dict={'Name':'Jack','Age':26}
>>> print(my_dict)
{'Age': 26, 'Name': 'Jack'}
>>> print(my_dict['Name'])
Jack
>>> print(my_dict.get('Age'))
26
>>> print(my_dict.get('Address'))
None
>>> print(my_dict['Address'])
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
>>> my_dict={'Name':'Jack','Age':26}
>>> print(my_dict)
{'Age': 26, 'Name': 'Jack'}
>>> my_dict['Age']=30
>>> print(my_dict)
{'Age': 30, 'Name': 'Jack'}
>>> my_dict['Address']='Nanded'
>>> print(my_dict)
{'Age': 30, 'Name': 'Jack', 'Address': 'Nanded'}
>>>
We can remove a particular item in a dictionary by using the method pop(). This method
removes as item with the provided key and returns the value.
>>> sqr={1:1,2:4,3:9,4:16,5:25}
>>> print(sqr)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> print(sqr.pop(4))
16
>>> print(sqr)
{1: 1, 2: 4, 3: 9, 5: 25}
>>> print(sqr.popitem())
(1, 1)
>>> print(sqr)
{2: 4, 3: 9, 5: 25}
>>> del sqr[5]
>>> print(sqr)
{2: 4, 3: 9}
>>> del sqr
>>> print(sqr)
>>> sqr.clear()
>>> print(sqr)
{}
Methods that are available with dictionary are tabulated below. Some of them have already
been used in the above examples.
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, Return a new dictionary with keys from seq and value equal to v (defaults
v]) to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
Remove the item with key and return its value or d if key is not found. If d
pop(key[,d])
is not provided and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.
If key is in the dictionary, return its value. If not, insert key with a value of
setdefault(key[,d])
d and return d (defaults to None).
Update the dictionary with the key/value pairs from other, overwriting
update([other])
existing keys.
values() Return a new view of the dictionary's values
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}
We can perform set operations like union, intersection on two sets. Set have unique values.
They eliminate duplicates.
Since, set are unordered collection, indexing has no meaning. Hence the slicing operator []
does not work.
Python has a set of built-in methods that you can use on sets.
Method Description
Tuple is an ordered sequence of items same as 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 list as it cannot change
dynamically.
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
Method Description
index() Searches the tuple for a specified value and returns the position of
where it was found