SlideShare a Scribd company logo
1 of 56
Download to read offline
Python Data Types
Number, String, List Data Types
Python Data Types
Variables can hold values, and every value has a data-type.
Python is a dynamically typed language; hence we do not need to define
the type of the variable while declaring it.
The interpreter implicitly binds the value with its type.
Python Data Types
a = 5
The variable a holds integer value five and we did not define its type.
Python interpreter will automatically interpret variables a as an integer type.
Python enables us to check the type of the variable used in the program.
Python provides us the type() function, which returns the type of the variable
passed.
NUMERIC DATA TYPE
Numeric Data Type
● Number stores numeric values.
● The integer, float, and complex values belong to a Python Numbers
data-type.
● Python provides the type() function to know the data-type of the variable.
● Similarly, the isinstance() function is used to check an object belongs to
a particular class.
Numbers
Python supports three types of numeric data.
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150
etc. Python has no restriction on the length of an integer. Its value
belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2,
etc. It is accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where
x and y denote the real and imaginary parts, respectively. The complex
numbers like 2.14j, 2.0 + 2.3j, etc.
Numbers
a = 5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Number Data Type : Examples
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Float
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Type Conversion
Output
……………………
1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
String Data Type
String
Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes.
Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
print(type(str)) #then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn't
support the character data-type;
instead, a single character written as 'p' is treated as the string of length 1.
String
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are
generally used for represent the
multiline or docstring'''
print(str3)
Strings indexing and splitting
Strings indexing and splitting
the slice operator [] is used to access
the individual characters of the
string.
However, we can use the : (colon)
operator in Python to access the
substring from the given string.
Strings indexing and splitting
We can do the negative slicing in the string; it starts from the rightmost character,
which is indicated as -1.
The second rightmost index indicates -2,
and so on.
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string.
The string object doesn't support item assignment i.e.,
A string can only be replaced with new string since its content cannot be
partially replaced.
Strings are immutable in Python.
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings
given either side of the operator.
* It is known as repetition operator. It concatenates the
multiple copies of the same string.
in It is known as membership operator. It returns if a particular
sub-string is present in the specified string.
not in It is also a membership operator and does the exact reverse
of in. It returns true if a particular substring is not present in
the specified string.
String Operators
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1) # prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
String
The format() method is the most flexible and useful method in formatting strings.
The curly braces {} are used as the placeholder in the string and replaced by the
format() method argument.
# Using Curly braces
print("{} and {} both are the best friend".format("Arun","Abhishek"))
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
String Concatenation
a = "Hello"
b = "World"
c = a + b
print(c)
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
LIST
Python List
● A list in Python is used to store the sequence of various types of data.
● Python lists are mutable type its mean we can modify its element after it created.
● 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 can be defined as below
1. L1 = ["John", 102, "USA"]
2. L2 = [1, 2, 3, 4, 5, 6]
List is a collection which is ordered and changeable.
Allows duplicate members.
List indexing and splitting
List indexing and splitting
Unlike other languages, Python provides the flexibility to use the negative indexing also.
The negative indices are counted from the right.
Updating List values
● Lists are the most versatile data structures in Python since they are
mutable, and their values can be updated by using the slice and
assignment operator.
● Python also provides append() and insert() methods, which can be used to
add values to the list.
Append Items in List
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Insert Items in List
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Remove List Items
The remove() method removes the specified item.
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Remove Specific Index Element
The pop() method removes the specified index.
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
Remove Specific Index Element
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
Remove Specific Index Element
The del keyword also removes the specified index:
Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Delete the list
The del keyword can also delete the list completely.
Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Loop Through a List
You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Sort List Alphanumerically
List objects have a sort() method that will sort the list alphanumerically, ascending, by
default:
Example
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
Sort the list numerically
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
Sort Descending
To sort descending, use the keyword argument reverse = True:
Example
Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Sort Descending
Sort the list descending:
thislist = [100, 50, 65, 82, 23]
thislist.sort(reverse = True)
print(thislist)
Copy a List
We cannot copy a list simply by typing list2 = list1, because: list2 will only be a
reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Copy a List
Another way to make a copy is to use the built-in method list().
Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Join Two Lists
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
LIST OPERATIONS
LIST OPERATIONS
LIST FUNCTIONS
Tuple
● Tuples are used to store multiple items in a single variable.
● A tuple is a collection which is ordered and unchangeable.
● Tuples are written with round brackets.
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple
● Tuple items are ordered, unchangeable, and allow duplicate values.
● Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
● When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
● Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created. (Immutable)
● Allow Duplicates : they can have items with the same value:
Tuple
T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50
T4 = (10,)
T5 = ()
Tuple indexing and slicing
The indexing and slicing in the tuple are similar to lists.
The indexing in the tuple starts from 0 and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the index [] operator.
Python also allows us to use the colon operator to access multiple items in the
tuple.
Tuple indexing and slicing
Tuple indexing
Negative Indexing
The tuple element can also access by using negative indexing.
The index of -1 denotes the rightmost element and -2 to the second last item
and so on.
Basic Tuple operations
Basic Tuple operations
Python Tuple inbuilt functions

More Related Content

What's hot

What's hot (20)

arrays in c
arrays in carrays in c
arrays in c
 
Presentation on array
Presentation on array Presentation on array
Presentation on array
 
Array operations
Array operationsArray operations
Array operations
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Quick sort
Quick sortQuick sort
Quick sort
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Array in c programming
Array in c programmingArray in c programming
Array in c programming
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
NUMBER SYSTEM
NUMBER SYSTEMNUMBER SYSTEM
NUMBER SYSTEM
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...
What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...
What are Data structures in Python? | List, Dictionary, Tuple Explained | Edu...
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Doubly linked list (animated)
Doubly linked list (animated)Doubly linked list (animated)
Doubly linked list (animated)
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 

Similar to Python Data Types (1).pdf

Similar to Python Data Types (1).pdf (20)

Python data type
Python data typePython data type
Python data type
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Data Handling
Data Handling Data Handling
Data Handling
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
List in Python
List in PythonList in Python
List in Python
 
Python
PythonPython
Python
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
unit 1.docx
unit 1.docxunit 1.docx
unit 1.docx
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196
 
Datatypes in Python.pdf
Datatypes in Python.pdfDatatypes in Python.pdf
Datatypes in Python.pdf
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 

Recently uploaded

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

Python Data Types (1).pdf

  • 1. Python Data Types Number, String, List Data Types
  • 2. Python Data Types Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence we do not need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type.
  • 3. Python Data Types a = 5 The variable a holds integer value five and we did not define its type. Python interpreter will automatically interpret variables a as an integer type. Python enables us to check the type of the variable used in the program. Python provides us the type() function, which returns the type of the variable passed.
  • 4.
  • 6. Numeric Data Type ● Number stores numeric values. ● The integer, float, and complex values belong to a Python Numbers data-type. ● Python provides the type() function to know the data-type of the variable. ● Similarly, the isinstance() function is used to check an object belongs to a particular class.
  • 7. Numbers Python supports three types of numeric data. 1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no restriction on the length of an integer. Its value belongs to int 2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto 15 decimal points. 3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
  • 8. Numbers a = 5 print("The type of a", type(a)) b = 40.5 print("The type of b", type(b)) c = 1+3j print("The type of c", type(c)) print(" c is a complex number", isinstance(1+3j,complex)) Output The type of a <class 'int'> The type of b <class 'float'> The type of c <class 'complex'> c is complex number: True
  • 9. Number Data Type : Examples Complex: x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) Float x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z)) Float x = 35e3 y = 12E4 z = -87.7e100 print(type(x)) print(type(y)) print(type(z))
  • 12. String Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. Syntax: str = "Hi Python !" Here, if we check the type of the variable str using a Python script print(type(str)) #then it will print a string (str). In Python, strings are treated as the sequence of characters, which means that Python doesn't support the character data-type; instead, a single character written as 'p' is treated as the string of length 1.
  • 13. String #Using single quotes str1 = 'Hello Python' print(str1) #Using double quotes str2 = "Hello Python" print(str2) #Using triple quotes str3 = '''''Triple quotes are generally used for represent the multiline or docstring''' print(str3)
  • 14. Strings indexing and splitting
  • 15. Strings indexing and splitting the slice operator [] is used to access the individual characters of the string. However, we can use the : (colon) operator in Python to access the substring from the given string.
  • 16. Strings indexing and splitting We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1. The second rightmost index indicates -2, and so on.
  • 17. Reassigning Strings Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are immutable in Python.
  • 18. String Operators Operator Description + It is known as concatenation operator used to join the strings given either side of the operator. * It is known as repetition operator. It concatenates the multiple copies of the same string. in It is known as membership operator. It returns if a particular sub-string is present in the specified string. not in It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string.
  • 19. String Operators str = "Hello" str1 = " world" print(str*3) # prints HelloHelloHello print(str+str1) # prints Hello world print(str[4]) # prints o print(str[2:4]); # prints ll print('w' in str) # prints false as w is not present in str print('wo' not in str1) # prints false as wo is present in str1.
  • 20. String The format() method is the most flexible and useful method in formatting strings. The curly braces {} are used as the placeholder in the string and replaced by the format() method argument. # Using Curly braces print("{} and {} both are the best friend".format("Arun","Abhishek")) #Positional Argument print("{1} and {0} best players ".format("Virat","Rohit")) #Keyword Argument print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
  • 21. String Concatenation a = "Hello" b = "World" c = a + b print(c) To add a space between them, add a " ": a = "Hello" b = "World" c = a + " " + b print(c)
  • 22. LIST
  • 23. Python List ● A list in Python is used to store the sequence of various types of data. ● Python lists are mutable type its mean we can modify its element after it created. ● 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 can be defined as below 1. L1 = ["John", 102, "USA"] 2. L2 = [1, 2, 3, 4, 5, 6] List is a collection which is ordered and changeable. Allows duplicate members.
  • 24. List indexing and splitting
  • 25. List indexing and splitting Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative indices are counted from the right.
  • 26. Updating List values ● Lists are the most versatile data structures in Python since they are mutable, and their values can be updated by using the slice and assignment operator. ● Python also provides append() and insert() methods, which can be used to add values to the list.
  • 27. Append Items in List To add an item to the end of the list, use the append() method: Example Using the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist)
  • 28. Insert Items in List To insert a list item at a specified index, use the insert() method. The insert() method inserts an item at the specified index: Example Insert an item as the second position: thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist)
  • 29. Remove List Items The remove() method removes the specified item. Example Remove "banana": thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist)
  • 30. Remove Specific Index Element The pop() method removes the specified index. Example Remove the second item: thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist)
  • 31. Remove Specific Index Element If you do not specify the index, the pop() method removes the last item. Example Remove the last item: thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist)
  • 32. Remove Specific Index Element The del keyword also removes the specified index: Example Remove the first item: thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist)
  • 33. Delete the list The del keyword can also delete the list completely. Example Delete the entire list: thislist = ["apple", "banana", "cherry"] del thislist
  • 34. Clear the List The clear() method empties the list. The list still remains, but it has no content. Example Clear the list content: thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist)
  • 35. Loop Through a List You can loop through the list items by using a for loop: Example Print all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist: print(x)
  • 36. Sort List Alphanumerically List objects have a sort() method that will sort the list alphanumerically, ascending, by default: Example Sort the list alphabetically: thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(thislist)
  • 37. Sort the list numerically thislist = [100, 50, 65, 82, 23] thislist.sort() print(thislist)
  • 38. Sort Descending To sort descending, use the keyword argument reverse = True: Example Sort the list descending: thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort(reverse = True) print(thislist)
  • 39. Sort Descending Sort the list descending: thislist = [100, 50, 65, 82, 23] thislist.sort(reverse = True) print(thislist)
  • 40. Copy a List We cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. There are ways to make a copy, one way is to use the built-in List method copy(). Example Make a copy of a list with the copy() method: thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist)
  • 41. Copy a List Another way to make a copy is to use the built-in method list(). Example Make a copy of a list with the list() method: thislist = ["apple", "banana", "cherry"] mylist = list(thislist) print(mylist)
  • 42. Join Two Lists There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator. Example Join two list: list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3)
  • 43. Join Two Lists Use the extend() method to add list2 at the end of list1: list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1)
  • 46.
  • 48. Tuple ● Tuples are used to store multiple items in a single variable. ● A tuple is a collection which is ordered and unchangeable. ● Tuples are written with round brackets. Create a Tuple: thistuple = ("apple", "banana", "cherry") print(thistuple)
  • 49. Tuple ● Tuple items are ordered, unchangeable, and allow duplicate values. ● Tuple items are indexed, the first item has index [0], the second item has index [1] etc. ● When we say that tuples are ordered, it means that the items have a defined order, and that order will not change. ● Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created. (Immutable) ● Allow Duplicates : they can have items with the same value:
  • 50. Tuple T1 = (101, "Peter", 22) T2 = ("Apple", "Banana", "Orange") T3 = 10,20,30,40,50 T4 = (10,) T5 = ()
  • 51. Tuple indexing and slicing The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from 0 and goes to length(tuple) - 1. The items in the tuple can be accessed by using the index [] operator. Python also allows us to use the colon operator to access multiple items in the tuple.
  • 53. Tuple indexing Negative Indexing The tuple element can also access by using negative indexing. The index of -1 denotes the rightmost element and -2 to the second last item and so on.
  • 56. Python Tuple inbuilt functions