Python Unit 3 Part 3,4
Python Unit 3 Part 3,4
Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Everything is an object in
Python programming, data types are actually classes and variables are instance (object) of these
classes.
Following are the standard or built-in data type of Python:
• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary
Note: Before going further, lets make it clear that in List, Tuple, Set and
Dictionary, many functions are same for these data structures
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value can be
integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.
• Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
• Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed
by a positive or negative integer may be appended to specify scientific notation.
• Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
# Python program to
# demonstrate numeric value
a=7
print("Type of a: ", type(a))
b = 6.7
print("\nType of b: ", type(b))
c = 3 + 7j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences allows
to store multiple values in an organized and efficient fashion. There are several sequence types in
Python –
• List
• Tuple
Python List
List in python is implemented to store the sequence of various type of data. However, python
contains six data types that are capable to store the sequences but the most common and reliable
type is list.
A list can be defined as a collection of values or items of different types. The items in the list are
separated with the comma (,) and enclosed with the square brackets [].
A list is a collection which is ordered and changeable (we can change the values of list).
Example 1
Create a List:
Output
The indexing is processed in the same way as it happens with the strings. The elements of the list
can be accessed by using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th
index, the second element of the list is stored at the 1st index, and so on.
Example 2
Output
We can also use for loop through the list items by using a for loop:
Example 3
Sanjeev
Khanna
Rajiv
By the membership operator ‘in’, we can determine if a specified item is present in a list.
Example 4
4. List Length
To determine how many items a list has, use the len() function:
Example 5
Output
5. Add Items
To add an item at the end of the list, use the append() method:
Example 6
Output
['Ram' , 'Shyam', 'Seeta', 'Geeta', 'Karan'] #Karan has been added at the end of list
Example 7
Output
New List- After adding Samsung at the 2nd index, the value of Apple will move to the 3rd index
and Nokia will move to the 4th index
7. Remove Item
Example 8
Output
The pop() method removes the last item.(if the index number will not be mentioned)
Output
['Microsoft', 'Samsung']
Example 10
The pop() method removes the specified item.(if the index number will be mentioned)
Output
['Microsoft', 'Nokia']
Example 11
Output
['Samsung', 'Nokia']
Example 12
Output
Output
[]
Python Tuple
A tuple is a collection which is ordered(fixed index number) and unchangeable. In Python
tuples are written with round brackets().
Python Tuple is used to store the sequence of immutable python objects. Tuple is similar to lists
since the value of the items stored in the list can be changed whereas the tuple is immutable and
the value of the items stored in the tuple can not be changed.
Example 14
Create a Tuple:
Output
We can access tuple items by referring to the index number, inside square brackets:
Example 15
Output
Apple
2. Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second last item etc.
Example 16
Note: As we know that we can’t make changes (addition or deletion of elements) in the tuple,
so there is not any function of append, pop or remove
Example 17
Output
Microsoft
Apple
Nokia
Example 18
5. Tuple Length
To determine how many items a tuple has, use the len() method:
Example 19
Output
6. Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example 20
When you are going to create a tuple with only one item, you have add a comma after the item,
unless Python will not recognize the variable as a tuple instead of it will recognize as string.
Example 21
pytuple = ("Apple",)
print(type(pytuple))
#NOT a tuple
pytuple = ("Apple")
print(type(pytuple))
Output
<class 'tuple'>
<class 'str'>
8. Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple
completely:
Example 22
The set in python can be defined as the unordered collection of various items enclosed within the
curly braces. The elements of the set cannot be duplicate. The elements of the python set must be
immutable.
Unlike other collections in python, there is no index attached to the elements of the set, i.e., we
cannot directly access any element of the set by the index. However, we can print them all
together or we can get the list of elements by looping through the set.
Example 23
Create a Set:
Output
Note: The set list is unordered, meaning: the items will appear in a random order. When you
will again print the above example, their order or index number will be changed.
1. Access Items
We cannot access items in a set by referring to an index, since sets are unordered, so the items
don’t have any permanent index.
But we can loop through the set items using a for loop, or also check if a specified value is
present in a set, by using the in keyword.
Example 24
Output
Nokia
Apple
Microsoft
Example 25
print("Nokia" in pyset)
Output
True
2. Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add more than one item to a set use the update() method.
Example 26
Output
Example 27
Output
To determine how many items a set has, use the len() method.
Example 28
Output
4. Remove Item
Example 29
Output
Note: If the item to remove does not exist, remove() will raise an error.
Example 30
Output
{'Microsoft', 'Nokia'}
Note: If the item to remove does not exist, discard() will NOT raise an error.
We can also use the pop(), method to remove an item, but this method will remove the last item.
But keep in remembrance that sets are unordered, so we will not know which item will be
removed.
Example 31
Output
Apple
{‘Microsoft’ , ‘Nokia’}
Note: Sets are unordered, so when using the pop() method, you will not know which item that
gets removed.
Example 32
Output
set()
Example 33
print(pyset) #this will raise an error because the set no longer exists
Output
Dictionary is used to implement the key-value pair in python. The dictionary is the data type in
python which can simulate the real-life data arrangement where some specific value exists for
some particular key.
In other words, we can say that a dictionary is the collection of key-value pairs where the value
can be any python object whereas the keys are the immutable python object, i.e., Numbers, string
or tuple.
Syntax:
Output
Note: The string should be in single or double quote and number will be without quote
2. Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example 35
Output
Electronics
The other method is called get() that will give us the same result as above example:
Example 36
Output
Aakash
You can change the value of a specific item by referring to its key name:
Example 37
Output
{'Name': 'Aakash', 'Branch': 'Electrical', 'Year': 2nd}
Likewise, list and tuple we can also loop through a dictionary by using a for loop. When looping
through a dictionary, the return values are the keys of the dictionary, but there are methods to
return the values as well.
Example 38
Output
Name
Branch
Year
Example 39
Output
Aakash
Electronics
2nd
Example 40
You can also use the values() function to return values of a dictionary:
Output
Aakash
Electronics
2nd
Example 41
Loop through both keys and values, by using the items() function:
Output
Name Aakash
Branch Electronics
Year 2nd
To check whether a specified key is present in a dictionary we will use the in keyword:
Example 42
Check if "Year" is present in the dictionary:
Output
6. Dictionary Length
With the help of len() method, we will determine how many items (key-value pairs) a dictionary
have.
Example 43
Output
7. Adding Items
To Add a new item to the dictionary, which will be done by using a new index key and assigning
a value to it:
Example 44
pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}
pydict["Semester"] = "Fourth"
print(pydict)
Output
{'Name': 'Aakash', 'Branch': 'Electonics', 'Year': 2nd, 'Semester': 'Fourth' }
8. Removing Items
Like other data structures, there are several methods to remove item or items from a dictionary:
Example 45
The pop() method removes the item with the specified key name:
Output
Example 46
The del keyword removes the item with the specified key name:
Output
Example 47
Output
Example 48
Output
{}
Python lambda (Anonymous Functions)
In Python, anonymous function means that a function is without a name. As we already study the
python functions where we state that def keyword is used to define the normal functions with the
function name and the lambda keyword is used to create anonymous functions(It don’t have any
function name).
• This function can have any number of arguments but only one expression, which is
evaluated and returned.
• One is free to use lambda functions wherever function objects are required.
• You need to keep in your knowledge that lambda functions are syntactically restricted to a
single expression.
• It has various uses in particular fields of programming besides other types of expressions in
functions.
Example 1
A lambda function that adds 10 to the number passed in as an argument, and print the result:
x = lambda a : a + 10
print(x(5))
Output
15
Example 2
A lambda function that multiplies argument a with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))
Output
30
1. Use of Lambda Function in python
We use lambda functions when we require a nameless function for a short period of time.
The filter() function in Python takes in a function and a list as arguments. The function is called
with all the items in the list and a new list is returned which contains items for which the
function evaluates to True.
Here is an example use of filter() function to filter out only even numbers from a list.
Output:
[4, 6, 8,12]
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.
Output