0% found this document useful (0 votes)
13 views23 pages

Python Unit 3 Part 3,4

Hello
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views23 pages

Python Unit 3 Part 3,4

Hello
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

Python Data Types

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:

pylist = ["Prakash", "Rahul", "Sanjay"]


print(pylist)

Output

['Prakash', 'Rahul', 'Sanjay']

1. L1 = ["Rakesh", 102, "India"]


2. L2 = [1, 2, 3, 4, 5, 6]
3. L3 = [1, "Raj"]
4. print(L1)
5. print(L2)
6. print(L3)

List indexing and splitting

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.

Consider the following example.


Unlike other languages, python provides us the flexibility to use the negative indexing also. The
negative indices are counted from the right. The last element (right most) of the list has the index
-1, its adjacent left element is present at the index -2 and so on until the left most element is .

Note: The rule of Slicing in List is same as of String.

1. Change Item Value


To change the value of a specific item, we will use the index number:

Example 2

Change the second item:

pylist = ["Table", "Chair", "Pen"] #Index Number[0,1,2]


pylist[1] = "Pencil" #Second value will be changed
print(pylist) #Printing the list

Output

['Table', 'Pencil', 'Pen']

2. Loop Through a List

We can also use for loop through the list items by using a for loop:

Example 3

Print all items in the list, one by one:

pylist = ["Sanjeev", "Khanna", "Rajiv"]


for x in pylist:
print(x)
Output

Sanjeev

Khanna

Rajiv

3. Check if Item Exists

By the membership operator ‘in’, we can determine if a specified item is present in a list.

Example 4

Check if "Raj" is present in the list:

pylist = ["Raj", "Sonu", "Paresh"]


if "Raj" in pylist:
print("Yes, 'Raj' is present in the list")

4. List Length

To determine how many items a list has, use the len() function:

Example 5

Print the number of items in the list:

pylist = ["Ram", "Shyam", "Seeta", "Geeta"]


print(len(pylist))

Output

5. Add Items

To add an item at the end of the list, use the append() method:

Example 6

Using the append() method to append(add) an item:

pylist = ["Ram", "Shyam", "Seeta" , "Geeta"]


pylist.append("Karan")
print(pylist)

Output
['Ram' , 'Shyam', 'Seeta', 'Geeta', 'Karan'] #Karan has been added at the end of list

6. To add an item at the specified index, use the insert() method:

Example 7

Insert an item at the second position of the list:

pylist = ["Microsoft", "Apple", "Nokia"]


pylist.insert(1, "Samsung")
print(pylist)

Output

['Microsoft' , 'Samsung' , 'Apple' , 'Nokia' ]

Adding Samsung at the 2nd index of the list

Microsoft Apple Nokia


0 1 2

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

Microsoft Samsung Apple Nokia


0 1 2 3

7. Remove Item

There are several methods to remove items from a list:

Example 8

The remove() method removes the specified item:

pylist = ["Microsoft ", "Samsung ", "Apple " , "Nokia "]


pylist.remove("Apple")
print(pylist)

Output

['Microsoft', 'Samsung', 'Nokia']


Example 9

The pop() method removes the last item.(if the index number will not be mentioned)

pylist = ["Microsoft", "Samsung", "Nokia"]


pylist.pop()
print(pylist)

Output

['Microsoft', 'Samsung']

Example 10

The pop() method removes the specified item.(if the index number will be mentioned)

pylist = ["Microsoft", "Samsung", "Nokia"]


pylist.pop(1)
print(pylist)

Output

['Microsoft', 'Nokia']

Example 11

The del keyword removes the specified index:

pylist = ["Microsoft", "Samsung", "Nokia"]


del pylist[0]
print(pylist)

Output

['Samsung', 'Nokia']

Example 12

The del keyword can also delete the list completely:

pylist = ["Microsoft", "Samsung", "Nokia"]


del pylist #this will cause an error because you have succsesfully deleted "list10".

Output

NameError: name 'pylist' is not defined


Example 13

The clear() method empties the list:

pylist = ["Microsoft", "Samsung", "Nokia"]


pylist.clear()
print(pylist)

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:

pytuple = ("Microsoft", "Apple", "Nokia")


print(pytuple)

Output

('Microsoft', 'Apple', 'Nokia')

1. Access Tuple Items

We can access tuple items by referring to the index number, inside square brackets:

Example 15

Print the second item in the tuple:

pytuple = ("Microsoft", "Apple", "Nokia")


print(pytuple[1])

Output

Apple

Microsoft Apple Nokia


0 1 2

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

Print the last item of the tuple:

pytuple = ("Microsoft", "Apple", "Nokia")


print(pytuple[-1])

Microsoft Apple Nokia


-3 -2 -1

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

3. Loop Through a Tuple

We can loop through the tuple items by using a for loop.

Example 17

Iterate through the items and print the values:

pytuple = ("Microsoft", "Apple", "Nokia")


for x in pytuple:
print(x)

Output

Microsoft

Apple

Nokia

4. Check if Item Exists

To determine if a specified item is present in a tuple use the in keyword:

Example 18

Check if "Apple" is present in the tuple:

pytuple = ("Microsoft", "Apple", "Nokia")


if "Apple" in pytuple:
print("Yes, 'Apple' is in the pytuple")
Output

Yes, 'Apple' is in the pytuple

5. Tuple Length

To determine how many items a tuple has, use the len() method:

Example 19

Print the number of items in the tuple:

pytuple= ("Microsoft", "Apple", "Nokia")


print(len(pytuple))

Output

6. Add Items

Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

Example 20

You cannot add items to a tuple:

pytuple = ("Microsoft", "Apple", "Nokia")


pytuple[3] = "Samsung" # This will raise an error
print(pytuple)

7. Create Tuple With One Item

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

One item tuple, remember the commma:

pytuple = ("Apple",)
print(type(pytuple))

#NOT a tuple
pytuple = ("Apple")
print(type(pytuple))
Output

<class 'tuple'>
<class 'str'>

8. Remove Items

Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple
completely:

Example 22

The del keyword can delete the tuple completely:

pytuple = ("Microsoft", "Apple", "Nokia")


del pytuple
print(pytuple) #this will raise an error because the tuple no longer exists
Python Set
A set is a collection which is unordered and unindexed. In Python sets are written with curly
brackets.

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:

pyset= {"Microsoft", "Apple", "Nokia"}


print(pyset)

Output

{‘Microsoft’ , ’Apple’ , ’Nokia’}

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

Loop through the set, and print the values:

pyset = {"Microsoft", "Apple", "Nokia"}


for x in pyset:
print(x)

Output

Nokia
Apple
Microsoft
Example 25

Check if "Nokia" is present in the set:

pyset = {"Microsoft", "Apple", "Nokia"}

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 one item to a set use the add() method.

To add more than one item to a set use the update() method.

Example 26

Add an item to a set, using the add() method:

pyset = {"Microsoft", "Apple", "Nokia"}


pyset.add("Oppo")
print(pyset)

Output

{' Microsoft', 'Apple', 'Oppo', 'Nokia'}

Example 27

Add multiple items to a set, using the update() method:

pyset = {"Microsoft", "Apple", "Nokia"}


pyset.update(["Oppo", "Huawei", "Samsung"])
print(pyset)

Output

{‘Microsoft’ , ‘Oppo’ , ‘Nokia’, ‘Huawei’, ‘Samsung’ ‘Apple’}


3. Get the Length of a Set

To determine how many items a set has, use the len() method.

Example 28

Get the number of items in a set:

pyset = {"Microsoft", "Apple", "Nokia"}


print(len(pyset))

Output

4. Remove Item

To remove an item in a set, use the remove(), or the discard() method.

Example 29

Remove "Nokia" by using the remove() method:

pyset = {"Microsoft", "Apple", "Nokia"}


pyset.remove("Nokia")
print(pyset)

Output

{' Microsoft', 'Apple'}

Note: If the item to remove does not exist, remove() will raise an error.

Example 30

Remove "Apple" by using the discard() method:

pyset = {"Microsoft", "Apple", "Nokia"}


pyset.discard("Apple")
print(pyset)

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.

The return value of the pop() method is the removed item.

Example 31

Remove the last item by using the pop() method:

pyset = {"Microsoft", "Apple", "Nokia"}


x = pyset.pop()
print(x)
print(pyset)

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

The clear() method empties the set:

pyset = {"Microsoft", "Apple", "Nokia"}


pyset.clear()
print(pyset)

Output

set()

Example 33

The del keyword will delete the set completely:

pyset = {"Microsoft", "Apple", "Nokia"}


del pyset

print(pyset) #this will raise an error because the set no longer exists

Output

NameError: name 'pyset' is not defined


Python Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries
are written with curly brackets, and they have keys and values.

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:

dict_name = {<Keyname1> : <Value>, < Keyname2> : <Value2> , <Keyname3> : <Value>}

Note: String should be in single or double quote

1. Create and print a dictionary:


Example 34
pydict = {"Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}
print(pydict)

Output

{'Name': 'Aakash', 'Branch': 'Electronics', 'Year': 2nd}

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

Get the value of the "Branch" key:

pydict={"Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


x = pydict["Branch"]
print(x)

Output

Electronics
The other method is called get() that will give us the same result as above example:

Example 36

Get the value of the "Name" key:

pydict={ "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


x = pydict.get ("Name")

Output

Aakash

3. Changing Values of Dictionary

You can change the value of a specific item by referring to its key name:

Example 37

Change the "Branch" to "Electrical"

pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


pydict["Branch"] = "Electrical"
print(pydict)

Output
{'Name': 'Aakash', 'Branch': 'Electrical', 'Year': 2nd}

4. Loop through a Dictionary

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

Print all key names in the dictionary, one by one:

pydict = {"Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


for x in pydict:
print(x)

Output
Name
Branch
Year
Example 39

Print all the values in the dictionary, one by one:

pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


for x in pydict:
print(pydict[x])

Output
Aakash
Electronics
2nd

Example 40

You can also use the values() function to return values of a dictionary:

pydict = { "Name": "Aakash", "Branch": "Electronics" , "year" : 2nd}


for x in pydict.values():
print(x)

Output
Aakash
Electronics
2nd

Example 41

Loop through both keys and values, by using the items() function:

pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


for x, y in pydict.items():
print(x, y)

Output
Name Aakash
Branch Electronics
Year 2nd

5. Check if Key Exists

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:

pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


if "Year" in pydict:
print("Yes, 'Year' is one of the keys in the pydict dictionary")

Output

Yes, 'Year' is one of the keys in the pydict dictionary

6. Dictionary Length

With the help of len() method, we will determine how many items (key-value pairs) a dictionary
have.

Example 43

Print the number of items in the dictionary:

pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


print(len(pydict))

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:

pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


pydict.pop("Year")
print(pydict)

Output

{'Name': 'Aakash', 'Branch': 'Electronics'}\

Example 46

The del keyword removes the item with the specified key name:

pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


del pydict["Branch"]
print(pydict)

Output

{'Name': 'Aakash', 'Year': '2nd'}\

Example 47

The del keyword can also delete the dictionary completely:

pydict = {"Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


del pydict
print(pydict) #this will cause an error because "pydict" no longer exists.

Output

NameError: name 'pydict' is not defined

Example 48

The clear() method empties the dictionary:

pydict = { "Name": "Aakash", "Branch": "Electronics" , "Year" : 2nd}


pydict.clear()
print(pydict)

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).

It has the following syntax:


lambda arguments: expression

• 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

Lambda functions can take any number of arguments:

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.

In Python, we generally use it as an argument to a higher-order function (a function that takes in


other functions as arguments). Lambda functions are used along with built-in functions
like filter(), map() etc.

a. Example use with filter()

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.

mylist = [1, 5, 4, 6, 8, 11, 3, 12]


newlist = list(filter(lambda x: (x%2 == 0) , mylist))
print(newlist)

Output:

[4, 6, 8,12]

b. 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.

mylist = [1, 5, 4, 6, 8, 11, 3, 12]


newlist = list(map(lambda x: x * 2 , mylist))
print(newlist)

Output

[2, 10, 8, 12, 16, 22, 6, 24]

You might also like