0% found this document useful (0 votes)
31 views64 pages

3 Datatypes

The document discusses different Python data types including lists. It provides details on how to create, access, modify, add and remove items from lists. It also covers sorting and joining lists.

Uploaded by

M Ashraf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views64 pages

3 Datatypes

The document discusses different Python data types including lists. It provides details on how to create, access, modify, add and remove items from lists. It also covers sorting and joining lists.

Uploaded by

M Ashraf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Artificial Intelligence

(AI)
Agenda

▰ Data Types
▰ List
▰ Tuple
▰ Dictionary
▰ Sets
▰ Byte and Bytearray
2
Data Types

A particular kind of data item, as defined by the values it


can take. OR
An attribute of data which tells the compiler or interpreter
how the programmer intends to use the data. OR
The classification or categorization of data items is
known as Data types.

3
Back to main
Data Types:

Text Type: str


Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset


Boolean Type: bool

Binary Types: bytes, bytearray


4
String: (str or text)

▰ Sequence of characters used to store text.


▰ It is a collection of one or more characters put in a
single quote, double-quote or triple quote.
▰ In Python a character is a string of length one.
▰ A string can also include digits and symbols;
however, it is treated as text.
▰ Also, there is indexing in python string to access the
character of the word

5
Accessing character of a String:

▰ A character also called element of a string can be


accessed with it's index number.
▰ In Python, index number starts with 0 in forward direction
and -1 in backward direction.

6
https://www.alphacodingskills.com/python/img/python-string.png
Example: Strings in Python using single
quotes
#String with single Quotes
String1 = 'Welcome to the AI Class'
print("String with the use of Single Quotes: ")
print(String1)
#String with double Quotes
String1 = "I'm a Python"
print("\nString with the use of Double Quotes: ")
print(String1)
# String with triple Quotes
String1 = '''I'm a Python and I live in a world of "AI"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
# String with triple Quotes allows multiple lines
String1 = '''AI
With
Python''’
print("\nCreating a multiline String: ") 7
print(String1)
Example: Accessing characters of String

#Access characters of String


String1 = "ArtificialIntelligence"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

8
String Slicing:

MyString = 'Learn Python'


print(MyString[0:5])
print(MyString[-12:-7],"\n")

print(MyString[6:])
print(MyString[:-7],"\n")

print(MyString[:])

Output:Learn
Learn

Python
Learn

Learn Python 9
String Concatenation:

We can join two strings by using + operator.

text_1 = 'Learn'
text_2 = 'Python'
MyString = text_1 + text_2
print(MyString)

MyString = text_1 + " " + text_2


print(MyString)

Output: LearnPython
Learn Python

10
Numeric:

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

11
Integers: (int)

▰ It is the most common numeric data type used to store


numbers (positive or negative whole numbers) without a
fractional component.
▰ In Python there is no limit to how long an integer value
can be.

12
Four forms of Integers:

We can represent int in 4 forms:

▰ Decimal form: it is by default and digits are from 0-9.


▰ Binary form: base-2, 0 and 1.
▰ Octal form: 0-7
▰ Hexadecimal: 0-9, A-F

13
▰ By default the answer of these four forms are in decimal
forms, so to change that we need to convert them.So,
Here:
▰ For converting into binary we will do : bin(15) -.> 0b1111
▰ For converting into octal : oct(100) -> 0o144
▰ For converting into hexadecimal : hex (1000) -> 0x3e8

14
Float:

▰ Float is also a numeric data type used to store


numbers that may have a fractional component
(real number with floating point representation).
▰ In float, we can only have decimal no binary, oct, or
hex. Eg: a=10.5 So when we see the type of “a” It
will be float type.

15
Complex Numbers:

Complex number is represented by complex class. It is specified as


(real part) + (imaginary part)j. Like A+bj

16
https://i.ytimg.com/vi/QUGmwPwtbpg/hqdefault.jpg
Complex Numbers:

▰ The real part can be binary, octal, or hex anything, but the
image should be decimal only.
▰ OB111 + 20j it is correct, But 14+ 0B101 it is incorrect.
▰ We can also take float values as well x=10.5+20.1j.
▰ Addition or subtraction of the complex numbers is simple. We
simply do addition or subtraction of the real part of both
numbers and imaginary parts of both numbers.

17
Example: Python program to demonstrate
numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

18
Boolean:

Data type with one of the two built-in values, True or False.
Sometimes a boolean value is also represented as 0 (for
false) and 1 (for true).
True and False with capital ‘T’ and ‘F’ are valid booleans
otherwise python will throw an error.
Non-Boolean objects can be evaluated in Boolean context
as well and determined to be true or false.

19
Example: Python program to demonstrate
boolean type

x = bool(5)

#display x:
print(x)

#display the data type of x:


print(type(x))

Output:
True
<class 'bool'>

20
Back to main
Sequence Type - Lists

The most basic data structure in Python is the sequence.

21
Back to main
Lists

Creating a list is as simple as putting different comma-separated


values between square brackets. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

22
Access List Items

❑ List items are indexed and you can access them by referring to
the index number:
Access Items Negative Indexing

Range of Negative Indexes

23
Access List Items

Range of Indexes

By leaving out the start value, the range will start at the first item:

By leaving out the end value, the range will go on to the end of the list:

24
Change List Items

Change Item Value Insert Items

Change a Range of Item Values

25
Change List Items

If you insert more items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:

If you insert less items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:

26
Add List Items

Append Items Insert Items

27
Add List Items

Extend List

Add Any Iterable

28
Remove List Items

Remove Specified Item Remove Specified Index

Remove Specified Index Clear the List

29
Sort Lists

Sort List Alphanumerically

Sort the list numerically:

30
Sort Lists

Sort Descending

31
Sort Lists

Case Insensitive Sort

Reverse Order

32
Copy Lists

Copy a List

There are ways to make a copy, copy() and list()

33
Join Lists

Join Two Lists

One of the easiest ways are by using the + operator.

Or you can use the extend() method, which purpose is


to add elements from one list to another list:

34
Basic List Operations

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

35
Built-in List Functions & Methods

Sr.No. Function with Description


1 len(list)
Gives the total length of the list.
2 max(list)
Returns item from the list with max value.
3 min(list)
Returns item from the list with min value.
4 list(seq)
Converts a tuple into list.

36
Built-in List Functions & Methods

Sr.No. Methods with Description


1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
37
Built-in List Functions & Methods

Sr.No. Methods with Description


6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given

38
Back to main
Tuples

▰ A tuple is a collection of objects separated by commas.


▰ It is similar to a list in terms of indexing, nested objects and
repetition but unlike lists a tuple is immutable.
# An empty tuple
empty_tuple = ()
print (empty_tuple)

Output: ()

▰ make sure to add a comma after the element, In case your


generating a tuple with a single element.

39
Back to main
Access Tuple Items:

Access Tuple Items Negative Indexing

Range of Indexes

40
Access Tuple Items:

Range of Negative Indexes

41
Update Tuples

Add Items Change Tuple Values


1. Convert into a list

2. Add tuple to a tuple

42
Update Tuples

Remove Items

You can delete the tuple completely

43
Join Tuples

Join Two Tuples Multiply Tuples

44
Basic Tuples Operations

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

45
Built-in Tuple Functions

Sr.No. Function with Description


1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
46
Sequence Types: Range()

range() was a built-in function that returned a list in


Python 2 but in python 3 it’s a datatype.
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12) [GCC 4.2.1
(Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright",
"credits" or "license" for more information.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> type(range(10))
<type 'list'>

47
Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13) [GCC
4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help",
"copyright", "credits" or "license" for more information.
>>> range(10)
range(0, 10)
>>> type(range(10))
<class 'range'>

Range returns a sequence of numbers starting from zero


and increment by 1 by default and stops before the
given number.
48
Syntax:

range (n)
Gives values to 0 to n-1
range(begin : end)
Gives values from the beginning to the n-1
Range (begin, end, increment/Decrement)
R = range(10)
R= range(1, 10)
R = range(1, 21,2 )
R= range (20, 1, -2)

49
Back to main
Mapping Type: Dictionary

▰ Dictionary is a collection of data values.


▰ It is used to store data unlike other Data Types that hold
only a single value as an element.
▰ Dictionary holds key:value pair.
▰ Dictionary can be created by placing a sequence of
elements within curly {} braces, separated by ‘comma’
and values can be assigned and accessed using square
braces []
▰ Dictionary Values are of any data type and can be
duplicated,whereas keys are case sensitive, can’t be
repeated and must be immutable. 50
Back to main
Syntax:

dic = { key1: value1, key2 : Value2}

Dictionary can also be created by the built-in function dict().


An empty dictionary can be created by just placing curly
braces{}.

dic = { }
#we can add values to empty dictionary like:
dic[key1] = value1
dic[key2] = value2

51
# Creating an empty Dictionary
Dict = {}
print(Dict)

# Creating a Dictionary with dict() method


Dict = dict({1: 'AI', 2: 'with', 3:'Python'})
print(Dict)

# Creating a Dictionary with each item as a Pair


Dict = dict([(1, 'AI'), (2, 'with')])
print(Dict)
Output:
{}
{1: 'AI', 2: 'with', 3: 'Python'}
{1: 'AI’, 2: 'with'}
52
Nested Dictionary:

▰ A Nested dictionary can be created in Python by placing the


comma-separated dictionaries enclosed within braces.
▰ Slicing Nested Dictionary is not possible.
▰ We can shrink or grow nested dictionaries as needed.
▰ Adding elements to a nested Dictionary can be done in
multiple ways.
▰ One way is to add values one by one.
Nesteddict[dict][key] = 'value'
▰ Another way is to add the whole dictionary in one go
Nesteddict[dict] = { 'key': 'value'}
53
Example:

# Python program to print Empty nested dictionary


dict = { 'dict1': { },
'dict2': { }, 'dict3': { }}
print("Nested dictionary are as follows -")
print(dict)

Dict = {'Name': 'python', 1: [11, 12, 13]}


print(Dict)

Here, we have used the concept of mixed keys, in which keys


are not the same. We will extend it and make a nested
dictionary with the same keys but different values.
54
Example:

here we have used the concept of the same keys, in which


keys are the same, but the corresponding data values are
different.
Dict = { 'Dict1': {'Name': 'amina', 'age': '22'},
'Dict2': {'Name': 'Asim', 'age': '19'}}
print("\n Nested dictionary 2-")
print(Dict)
Output:
Nested dictionary 2-
{'Dict1': {'Name': 'amna', 'age': '22'}, 'Dict2': {'Name': 'Asim', 'age': '19'}}

55
Back to main
Creating an empty set

Creating an empty set is a bit tricky.Empty curly braces {} will


make an empty dictionary in Python. To make a set without
any elements, we use the set() function without any argument.
# creation of empty set and dictionary
# initialize a with {}
a = {}
# check data type of a
print(type(a))
# initialize a with set()
a = set()
# check data type of a
print(type(a))
Output: <class 'dict'>
<class 'set'> 56
Back to main
Adding and Removing elements

It can have any number of items and they may be of different


types (integer, float, tuple, string etc.). # set of integers
my_set = {1, 2, 3}
We can add and remove elements form the set by: print(my_set)
add(): Adds a given element to a set # set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
clear(): Removes all elements from the set print(my_set)

Output: {1, 2, 3}
discard(): Removes the element from the set
{1.0, (1, 2, 3), 'Hello'}
remove(): Removes the element from the set
pop(): Returns and removes a random element from the set

57
Add Set Items

Add Items Add Any Iterable

Add Sets

58
Remove Set Items

Remove Item

59
Combining Sets

Union of set1 and set2 is a set of all elements from


both sets.

60
The intersection and difference

Intersection of A and B is a set of elements that are common in


both the sets. A = {1, 2, 3, 4, 5}
A = {1, 2, 3, 4, 5} B = {3, 4, 5, 6, 7, 8}
B = {3, 4, 5, 6, 7, 8} A.difference(B)
A.intersection(B) B.difference(A)

Output: {3, 4, 5} Output: {1, 2}


Output: {6, 7, 8}

Difference of the set B from set A(A - B) is a set of elements that


are only in A but not in B. Similarly, B - A is a set of elements in B
but not in A.
61
Example:

# random dictionary
person = {"name": "Abid", "age": 24,
"Gender": "male"}

fSet = frozenset(person)
print('The frozen set is:', fSet)
Output: The frozen set is: frozenset({'name',
'gender', 'age'})

Like normal sets, frozenset can also perform different


operations like copy, difference, intersection and union.

62
Bytes and BytesArray

Here we have list li= [10, 20,30,40], to convert it into the bytes we need
to do is b=bytes(li),Now it converted into binary data for creation.
Bytes can only have values from 0 to 256. So basically, if we add the
value 256, 257 … We will get the value error.
Now in this as well indexing, slicing is there,But it is immutable (we
cannot change its content) We will get an error. But if we want mutable
bytes then it is known as Bytearray

63
Back to main
None Data Type:

None data type is nothing i.e no value is associated with it. To


make the value available for the garbage collection.

a=None
Print (type(a))

64

You might also like