Data Types in Python
Unit-3&4
Data types in Python
Every value in Python has a datatype. Since everything is an object in Python
programming, data types are actually classes and variables are instance
(object) of these classes. Some of the datatypes in Python are:-
Python Numbers
Python Strings
Python List
Python Tuple
Python Dictionary
Number Data Type in Python
Python supports integers, floating point numbers and complex numbers.
They are defined as int, float and complex class in Python.
Integers and floating points are separated by the presence or absence of
a decimal point. 5 is integer whereas 5.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.
Number Data Type in Python
We can use the type() function to know which class a variable or a value
belongs to and isinstance() function to check if it belongs to a particular
class.
Python List
List is an ordered sequence of items. All the items in a list do not
need to be of the same type.
List is a collection which is ordered and changeable. It allows
duplicate members.
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.).
Lists are mutable, and hence, they can be altered even after their
creation.
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.
Python List
e.g.
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Python List
Also, a list can even have another list as an item. This is called nested
list.
e.g.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Adding elements to a List
Using append():
Elements can be added to the List by using built-in append() function.
Only one element at a time can be added to the list by using append() method,
for addition of multiple elements with the append() method, loops are used.
Adding elements to a List
Using insert() method:
append() method only works for addition of elements at the end of the List,
for addition of element at the desired position, insert() method is
used.
Unlike append() which takes only one argument, insert() method requires two
arguments(position, value).
Adding elements to a List
Using extend() method:
extend(), this method is used to add multiple elements at the same time at
the end of the list.
Access elements from a list
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.
Nested list are accessed using nested indexing.
Access
Negative Indexing:
elements from a list
In Python, negative sequence indexes represent positions from the end
of the array.
Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second last item etc
E.g. my_list = ['p','r','o','b','e']
Removing elements from the List
Using remove() method:
Elements can be removed from the List by using built-in remove() function but an
Error arises if element doesn’t exist in the set.
Remove() method only removes one element at a time, to remove range of
elements, iterator is used. remove() method is used to remove the given item.
If a list contains duplicate elements, the remove() method only removes the first
matching element.
The syntax of the remove() method is:
list.remove(element)
Removing elements from the List
The syntax of the pop() method is:
list.pop(index)
The pop() method takes a single argument (index).
The argument passed to the method is optional. If not passed, the
default index -1 is passed as an argument (index of the last item).
Removing elements from the List
del[a : b] :-
This method deletes all the elements in range starting from index ‘a’ till
‘b’ mentioned in arguments.
a=[1,2,3,4,5]
del a[0:3]
print(a)
Slicing of a List
To print a specific range of elements from the list, we use Slice
operation. Slice operation is performed on Lists with the use of colon(:).
To print elements from beginning to a range use [:Index],
to print elements from end use [:-Index],
to print elements from specific Index till the end use [Index:],
to print elements within a range, use [Start Index:End Index] and
to print whole List with the use of slicing operation, use [:].
Further, to print whole List in reverse order, use [::-1].
List Methods in Python
len() :- This function returns the length of list.
min() :- This function returns the minimum element of list.
max() :- This function returns the maximum element of list.
print (len(list))
print (min(list))
print (max(list))
List Methods in Python
count() :- This function counts the number of occurrences of
elements in list.
print (lis.count(3))
sum() : Calculates sum of all the elements of List.
Syntax: sum(List)
length:Calculates total length of List.
Syntax:len(list_name)
Tuple in Python
A Tuple is a collection of Python objects separated by commas.
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, in a list, elements can be changed i.e. a tuple is immutable
unlike lists which are mutable.
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.).
Creating a Tuple
A tuple can also be created without using parentheses. This is
known as tuple packing.
Packing and Unpacking a Tuple : In Python there is a very
powerful tuple assignment feature that assigns right hand side of
values into left hand side. In other way it is called unpacking of a
tuple of values into a variable. In packing, we put values into a
new tuple while in unpacking we extract those values into a single
variable.
In unpacking of tuple number of variables on left hand side should
be equal to number of values in given tuple.
Creating a tuple with one element
Having one element within parentheses is not enough. We will need a
trailing comma to indicate that it is, in fact, a tuple.
Access Tuple Elements
We can use the index operator [] to access an item in a tuple where the
index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5.
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.
Slicing
We can access a range of items in a tuple by using the slicing operator -
colon ":".
my_tuple = ('p','r','o','g','r','a','m','i','z')
# elements 2nd to 4th
#Output: ('r', 'o', 'g')
print(my_tuple[1:4])
Slicing
Slicing can be best visualized by considering the index to be between
the elements as shown below. So if we want to access a range, we need
the index that will slice the portion from the tuple.
Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once it has been
assigned. But, if the element is itself a mutable datatype like list, its
nested items can be changed.
We can also assign a tuple to different values (reassignment).
Mutable vs Immutable i.e. (List vs
Tuple)
a variable is nothing but a reference to the actual python object in
memory.
The variable itself is not the object.
Variable and Python object
a = ["apples", "bananas", "oranges"]
When you do this, a python object of type list is created in the memory
and the variable a refers to this object by holding its location in
memory.
In case of List
In Case of Tuple