You are on page 1of 51

By – Amresh Tiwari (SGEI)

Data type identifies the type of data


values a variable can hold and the
operations that can be performed on
that data.
Variables can hold values of different
data types.

Python Data
Python is a dynamically typed language
Types hence we need not define the type of
the variable while declaring it.

The interpreter implicitly binds the value


with its type.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Sequence
• A Python sequence is an ordered collection of items, where
each item is indexed by an integer.
• The three types of sequence data types available in Python are
Strings, Lists and Tuples.
• Note:

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


The string can be defined as the
sequence of characters represented
in the quotation marks.

String
In python, we can use single,
double, or triple quotes to define a
string.

str1 = ”Good Morning” #string str1


Eg.
str2 = ' how are you’ #string str2

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


List is a sequence of items
separated by commas and the
items are enclosed in square
brackets [ ].

List Example #To create a list


>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Tuple is a sequence of items
separated by commas and items are
enclosed in parenthesis ( ).

This is unlike list, where values are

Tuple enclosed in brackets [ ]. Once


created, we cannot change the
tuple.

#create a tuple tuple1


>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
Eg. #print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Mutable and Immutable Data Types
• Variables whose values can be changed after they are created
and assigned are called mutable.
• Variables whose values cannot be changed after they are
created and assigned are called immutable.
• When an attempt is made to update the value of an immutable
variable, the old variable is destroyed and a new variable is
created by the same name in memory.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Mutable and Immutable Data Types

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


In the Python programming language, there are
four collection data types :

List is a collection which is ordered and


changeable. Allows duplicate members.
Python Collections Tuple is a collection which is ordered and
unchangeable. Allows duplicate members.
(Arrays)
Set is a collection which is unordered and
unindexed. No duplicate members.

Dictionary is a collection which is unordered,


changeable and indexed. No duplicate members.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


The list is a most versatile datatype available
in Python which can be written as a list of
comma-separated values (items) inside a
square brackets.

Python lists are ordered and mutable type


Python Lists (changeable), its mean we can modify its
element after it created.

Important point about a list is that items in a


list need not be of the same type (integer,
float, string, etc.).

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Creating a list is as simple as putting
different comma-separated values
between square brackets.

Creating a Syntax: list_name = [item1, item2, item3, ….]

list
Eg. List1 = [1,2,3,4,5]
list2 = [‘a’, ’b’, ‘c’, ‘d’, ‘e’]
list3 = [1, “Name”, 1.5]

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


• We can create empty list object by giving no
elements in square brackets in assignment
statement.

• Syntax: list_name = [ ]

Empty List • Eg. My_list=[ ]

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Nested List
• A list having another list as an item is called
nested list.

• Syntax:
list_name = [L1_Value, L1_Value,
[L2_Value, L2_Value, ….]]

Eg. A=[[11, 12, 13], [21, 22, 23], [31, 32, 33]]

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


The printing of the list is same as
of the printing of variables . the
print() function is used to print
the lists.

Printing Lists
Syntax : print(list_name)

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Accessing elements or items from the lists
There are various ways in which we can access the elements of a list.

Accessing individual items from the list.

Negative indexing

Range of index

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Accessing individual items from the list

• We can use the index operator [] to access an


item in a list.
• In Python, indices starts from 0. So, a list having
4 elements will have an index from 0 to 3.
• Eg. print(z[0]) will print 3.
print(z[1]) will print 7.

Note:- The index must be an integer.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Negative indexing

• Python allows negative indexing for its


sequences.
• The negative indexing means the
beginning from end ( right to left).
• Eg. print(z[-1]) will print 2.
print(z[-4]) will print 3.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


TRAVERSING A LIST

We can access each element of


the list or traverse a list using a
for loop or a while loop.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


TRAVERSING A LIST (Using for Loop)

• List Traversal Using for • Another way of accessing the


Loop: elements of the list is using
range() and len() functions:
>>> z= [3,7,4,2]
>>> for item in z: >>> z= [3,7,4,2]
print(item) >>> for item in range(len(z)):
print(z[item])
Output: Output:
3 3
7 7
4 4
2 2 By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
TRAVERSING A LIST (Using while Loop)

>>> i = 0
>>> while i < len(z):
print(z[i])
i += 1
Output:
3
7
4
2 By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Range of indexes (Slicing)
• We can specify a range of
indexes by specifying from
where to start and where to end
the range.
• We can access a range of items
in a list by using the slicing
operator : (colon).
• Slicing is used to extract a part of
the list.
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Range of indexes (Slicing)…
• >>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black']

• >>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']

• #list1 is truncated to the end of the list


>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow', 'Black']

• >>> list1[7:2] #first index > second index


[] #results in an empty list
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Range of indexes (Slicing)…

• >>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black']

• #slicing with a given step size


>>> list1[0:6:2]
['Red','Blue','Magenta']

• #negative indexes #elements at index -6,-5,-4,-3 are sliced


>>> list1[-6:-2]
['Green','Blue','Cyan','Magenta']
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
Range of indexes (Slicing)…

• >>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black']

• #both first and last index missing


>>> list1[::2] #step size 2 on entire list
['Red','Blue','Magenta','Black']

• #negative step size #whole list in the reverse order


>>> list1[::-1]
['Black','Yellow','Magenta','Cyan','Blue', 'Green','Red']
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
LIST METHODS AND BUILT-IN FUNCTIONS
• The data type list has several built-in methods that are useful
in programming.
• Some of them are –
len(), list(), append(), extend(), insert(), count(), index(),
remove(), pop(), reverse(), sort(), sorted(), min(), max(),
sum()

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Changing the Item value

Adding items in the list


List
Operations Deleting Items from the list

Finding the length of the list

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Lists are mutable, meaning their elements can be changed .
We can use the assignment operator (=) to change an item
or a range of items.

Changing
the Item
value

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Adding items in the list
We can add item(s) in a list by using any of the following method or function-

append() – This method add one item to the end of the list.

extend() - This method adds all the elements of a list to the end of the current list.

insert() – This method inserts an item at the defined index.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


For eg.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


• We can also use + (plus) operator to combine
two lists. This is called the concatenation of two
lists.
• The * operator repeats a list for the given
number of times.
Concatenate
&
Replicate
Operator

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Deleting Items from the list
We can delete item(s) in a list by using any of the following method or function-

remove() – This method removes an item from the list.

pop() – This method removes and returns an element at the given index. And removes
the last item if index is not provided.

clear() – This method removes all items from the list. i.e. empty a list.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


For eg.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


We can delete one or more
items from a list using the
keyword del.
del keyword
in Python
It can even delete the list
entirely.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


For eg.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


Finding the length of the list

To determine the
number of items in
a list, we use the
len() method.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


For eg.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


list()
• Creates an empty list if no argument is passed.
• Eg.- >>> list1 = list()
>>> list1
[]
• Creates a list if a sequence is passed as an argument
Eg.- >>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
count()
• Returns the number of times a given element
appears in the list.
• Eg.-
>>> list1 = [10,20,30,10,40,10]
>>> list1.count(10)
3
>>> list1.count(90)
0
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
index()
• Returns index of the first occurrence of the
element in the list. If the element is not present,
ValueError is generated
• Eg.-
>>> list1 = [10,20,30,10,40,10]
>>> list1.index(20)
1
>>> list1.index(90)
ValueError: 90 is not in list
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
reverse()
• Reverses the order of elements in the given list
Eg.-
>>> list1 = [10,20,30,40,50]
>>> list1.reverse()
>>> list1
[50,40,30,20,10]
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
sort()
• Sorts the elements of the given list in-place
• Eg.-
>>>list1=['Tiger','Zebra','Lion','Cat','Elephant' ,'Dog']
>>> list1.sort()
>>>list1
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra']
• Eg.-
>>> list1 = [34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
sorted()
• It takes a list as parameter and creates a new list consisting
of the same elements arranged in sorted order
• Eg.-
>>> list1 = [23,45,11,67,85,56]
>>> list2 = sorted(list1)
>>> list1
[23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


min(), max(), sum()
Eg.-
• min() - Returns minimum or
>>>list1= [34,12,63,39,92,44]
smallest element of the list >>> min(list1)
• max() - Returns maximum or 12
largest element of the list. >>> max(list1)
92
• sum() - Returns sum of the >>> sum(list1)
elements of the list 284

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


COPYING LISTS
• The simplest way to make a copy of the list is to assign
it to another list.
• Eg.- The statement list2 = list1 does not
>>> list1 = [1,2,3] create a new list. Rather, it just
>>> list2 = list1 makes list1 and list2 refer to the
same list object.
>>> list1
Here list2 actually becomes an
[1, 2, 3]
alias of list1. Therefore, any
>>> list2 changes made to either of them
[1, 2, 3] will be reflected in the other list.
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
COPYING LISTS…
• We can also create a copy or clone of the list as
a distinct object by three methods.
• The first method uses slicing, the second
method uses built-in function list() and the third
method uses copy() function of python library
copy.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


COPYING LISTS…
• Method-1 We can slice our original list and store it
into a new variable as follows:
newList = oldList[:]
Example
>>> list1 = [1,2,3,4,5]
>>> list2 = list1[:]
>>> list2
[1, 2, 3, 4, 5]
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
COPYING LISTS…
• Method-2 We can use the built-in function list() as
follows:
newList = list(oldList)
Example
>>> list1 = [10,20,30,40]
>>> list2 = list(list1)
>>> list2
[10, 20, 30, 40]
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)
COPYING LISTS…
• Method-3 We can use the copy () function as follows:
import copy #import the library copy
#use copy()function of library copy
newList = copy.copy(oldList)
• Example
>>> import copy
>>> list1 = [1,2,3,4,5]
>>> list2 = copy.copy(list1)
>>> list2
[1, 2, 3, 4, 5]

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


PROGRAMMING PROBLEMS
• Write a program to find the number of times an element
occurs in the list.
• Write a program to read a list of n integers and find their
median.
Note: The median value of a list of values is the middle one when they are arranged in
order. If there are two middle values then take their average.
Hint: You can use an built-in function to sort the list.
• Write a program to read a list of elements. Input an
element from the user that has to be inserted in the list.
Also input the position at which it is to be inserted. Write
a user defined function to insert the element at the
desired position in the list.

By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)


What will be the output of the following code segment:

a. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)
b. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)
c. list1 = [1,2,3,4,5]
print(list1[len(list1)-1])
By-Amresh Tiwari, Sunbeam Suncity (School & Hostel)

You might also like