SlideShare a Scribd company logo
1 of 14
PYTHON
SETS DICT
By,
Prof. Sharath H A,
Asst. Prof.,
Dept. of ISE,
MIT Mysore
CONTENT
Data type
 String
Data Structure
 List
 Tuples
 Sets
 Dictionaries
User defined data structures are – Stacks , Queues, Trees, Graphs,
Linked list, and Hash Maps
2
Inbuilt data structures
DATA-STRUCTURES
Types of Data Structures
 Strings – immutable ordered sequence of characters
EX: S = ‘abc’ or S = “abc” or S = ‘‘‘abc’’’
 List – mutable ordered sequence of objects
EX: L = [1,2,’a’]
 Tuples – immutable ordered sequence of objects
EX: T = (1,2,’a’)
 Sets – mutable unordered sequence of unique element
EX: S = {1,2,3}
Frozensets – same as Sets but it is immutable
EX: FS = frozenset(s)
 Dictionaries – mutable unordered collection of value pairs (mapping unique
key to value)
EX: D = ({1:’Karnataka’},{2:’Kerala’},{3:’Tamil Nadu’})
3
TERMINOLOGIES
Ordered and Unordered click_here
 Ordered/Indexed – Ordered means that the data structure retains the ordering as
provided by the programmer Ex: String, List and Tuples
 Unordered - Non ordered means that the data structure doesn’t have a specific order,
and doesn’t care about any ordering by the programmer Ex: Ex: Sets and Dictionaries
Mutable and Immutable
 Mutable – Mutable is when something is changeable or has the ability to change.
In Python, ‘mutable’ is the ability of objects to change their values.
Ex: List, Set and Dictionary
 Immutable - Immutable is the when no change is possible over time.
In Python, if the value of an object cannot be changed over time, then it is known
as immutable. Once created, the value of these objects is permanent
Ex: Strings, Tuples and Frozen-sets
4
COMPRESSION
String List Tuples Sets Dictionaries
Immutable Mutable Immutable Mutable Mutable
Ordered/Index Ordered/Index Ordered/Index Unordered unordered
Allows Duplicate
member
Allows Duplicate
member
Allows Duplicate
member
Not allows Duplicate
member
Not allows Duplicate
member
Empty string
S = “ ”
Empty list
L = [ ]
Empty tuple
T = ( )
Empty set
S = set{ }
Empty Dictionary
D = { }
String with single
character
S = “c”
List with single
Element
L = [ “Hello”]
Tuple with single
Element
T = ( “Hello”,)
List with single
Element
S = set { 1 }
List with single
Element
D = { “a”:1}
It can store any
datatype: int, str,
list, tuple, set and
dictionary
It can store any
datatype: int,
string, list, tuple,
set and dictionary
It can store any
datatype: int, str and
tuple
Key can be int, str
and tuple
Value can be int, str,
list, tuple, set and
dictionary
5
Strings in python are surrounded by either single quotation marks,
or double quotation marks. 'hello' is the same as "hello".
 Syntax:
v_name = “User String”
 Example:
S = “Hello world!”
name = “Sharath”
can display a string literal with the print() function:
print(s)
print(name)
6
Multiline strings: We can assign a multiline string to a variable by using
three quotes:
Example:
My_self = ‘‘‘Mr. Sharath H A,
Asst. Prof.,
Dept. of ISE,
MIT Mysore.’’’
My_self = “ “ “Mr. Sharath H A,
Asst. Prof.,
Dept. of ISE,
MIT Mysore.” ” ”
7
OUTPUT:
Mr. Sharath H A,
Asst. Prof.,
Dept. of ISE,
MIT Mysore.
Strings are Arrays: Python does not have a character data type, a single
character is simply a string with a length of 1
Square brackets can be used to access elements of the string.
Example:
a = ‘Hello’
print(a[1])
8
OUTPUT:
e
Note: remember that the first character has the position 0
Slicing: Specify the start index and the end index, separated by a colon, to
return a part of the string
Example:
a = ‘Hello World!’
print(a[1:5])
Slicing from the start: By leaving out the start index, the range will start
at the first character
Example:
a = ‘Hello World!’
print(a[:5])
Slice to the end: By leaving out the end index, the range will go to the end
Example:
a = ‘Hello World!’
print(a[7:])
9
OUTPUT:
ello
OUTPUT:
Hello
OUTPUT:
World!
Negative Indexing: Use negative indexes to start the slice from the end of
the string
Example:
a = ‘Hello World!’
print(a[-6:-2])
Slicing from the start: By leaving out the start index, the range will start
at the first character
Example:
a = ‘Hello World!’
print([:-2])
Slice to the end: By leaving out the end index, the range will go to the end
Example:
a = ‘Hello World!’
print(a[-6:])
10
OUTPUT:
Worl
OUTPUT:
Hello Worl
OUTPUT:
World!
Modify Strings: Python has a set of built-in methods that you can use on
strings
Upper Case - upper()
a = "Hello, World!"
print(a.upper())
Lower Case-lower()
a = "Hello, World!"
print(a.lower())
Remove Whitespace – strip()
a = " Hello, World! "
print(a.strip())
11
Replace string- replace()
a = "Hello, World!"
print(a.replace(“Hello”,“Bellow”))
Split String-split()
a = "Hello, World!"
print(a.split(“,”))
String Concatenation: To concatenate, or combine, two strings you can use
the + operator
Merge variable a with variable b into variable c
a = "Hello"
b = "World"
c = a + b
print(c)
c = a + " " + b
print(c)
12
String Format: As we learned in the Python Variables chapter, we cannot
combine strings and numbers like this
age = 36
txt = "My name is John, I am " + age
print(txt)
Use the format() method to insert numbers into strings
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
13
String Format:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
14

More Related Content

What's hot (18)

Perl_Tutorial_v1
Perl_Tutorial_v1Perl_Tutorial_v1
Perl_Tutorial_v1
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
PHP Unit 4 arrays
PHP Unit 4 arraysPHP Unit 4 arrays
PHP Unit 4 arrays
 
Pa1 session 3_slides
Pa1 session 3_slidesPa1 session 3_slides
Pa1 session 3_slides
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Python list
Python listPython list
Python list
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
 
Pa1 lists subset
Pa1 lists subsetPa1 lists subset
Pa1 lists subset
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
Python data types
Python   data typesPython   data types
Python data types
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
Groovy
GroovyGroovy
Groovy
 
Dictionaries IN SWIFT
Dictionaries IN SWIFTDictionaries IN SWIFT
Dictionaries IN SWIFT
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Array in php
Array in phpArray in php
Array in php
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 

Similar to Python ds

Data structures in Python
Data structures in PythonData structures in Python
Data structures in PythonMITULJAMANG
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
Data Structure and Algorithm Lesson 2.pptx
Data Structure and Algorithm Lesson 2.pptxData Structure and Algorithm Lesson 2.pptx
Data Structure and Algorithm Lesson 2.pptxJoannahClaireAlforqu
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfomprakashmeena48
 
math.pptx
math.pptxmath.pptx
math.pptxLaukik7
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docSrikrishnaVundavalli
 
Explore the foundational concepts of sets in discrete mathematics
Explore the foundational concepts of sets in discrete mathematicsExplore the foundational concepts of sets in discrete mathematics
Explore the foundational concepts of sets in discrete mathematicsDr Chetan Bawankar
 
varthini python .pptx
varthini python .pptxvarthini python .pptx
varthini python .pptxMJeyavarthini
 
The Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxThe Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxKavitha713564
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
Array,lists and hashes in perl
Array,lists and hashes in perlArray,lists and hashes in perl
Array,lists and hashes in perlsana mateen
 

Similar to Python ds (20)

Data structures in Python
Data structures in PythonData structures in Python
Data structures in Python
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
dataStructuresInPython.pptx
dataStructuresInPython.pptxdataStructuresInPython.pptx
dataStructuresInPython.pptx
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Python data handling
Python data handlingPython data handling
Python data handling
 
Sixth session
Sixth sessionSixth session
Sixth session
 
Data Structure and Algorithm Lesson 2.pptx
Data Structure and Algorithm Lesson 2.pptxData Structure and Algorithm Lesson 2.pptx
Data Structure and Algorithm Lesson 2.pptx
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
 
Lecture-5.pdf
Lecture-5.pdfLecture-5.pdf
Lecture-5.pdf
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
math.pptx
math.pptxmath.pptx
math.pptx
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Explore the foundational concepts of sets in discrete mathematics
Explore the foundational concepts of sets in discrete mathematicsExplore the foundational concepts of sets in discrete mathematics
Explore the foundational concepts of sets in discrete mathematics
 
varthini python .pptx
varthini python .pptxvarthini python .pptx
varthini python .pptx
 
The Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxThe Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptx
 
Numpy
NumpyNumpy
Numpy
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Array,lists and hashes in perl
Array,lists and hashes in perlArray,lists and hashes in perl
Array,lists and hashes in perl
 

Recently uploaded

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
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
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
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
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
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)

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
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...
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
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
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
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 ds

  • 1. PYTHON SETS DICT By, Prof. Sharath H A, Asst. Prof., Dept. of ISE, MIT Mysore
  • 2. CONTENT Data type  String Data Structure  List  Tuples  Sets  Dictionaries User defined data structures are – Stacks , Queues, Trees, Graphs, Linked list, and Hash Maps 2 Inbuilt data structures
  • 3. DATA-STRUCTURES Types of Data Structures  Strings – immutable ordered sequence of characters EX: S = ‘abc’ or S = “abc” or S = ‘‘‘abc’’’  List – mutable ordered sequence of objects EX: L = [1,2,’a’]  Tuples – immutable ordered sequence of objects EX: T = (1,2,’a’)  Sets – mutable unordered sequence of unique element EX: S = {1,2,3} Frozensets – same as Sets but it is immutable EX: FS = frozenset(s)  Dictionaries – mutable unordered collection of value pairs (mapping unique key to value) EX: D = ({1:’Karnataka’},{2:’Kerala’},{3:’Tamil Nadu’}) 3
  • 4. TERMINOLOGIES Ordered and Unordered click_here  Ordered/Indexed – Ordered means that the data structure retains the ordering as provided by the programmer Ex: String, List and Tuples  Unordered - Non ordered means that the data structure doesn’t have a specific order, and doesn’t care about any ordering by the programmer Ex: Ex: Sets and Dictionaries Mutable and Immutable  Mutable – Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. Ex: List, Set and Dictionary  Immutable - Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent Ex: Strings, Tuples and Frozen-sets 4
  • 5. COMPRESSION String List Tuples Sets Dictionaries Immutable Mutable Immutable Mutable Mutable Ordered/Index Ordered/Index Ordered/Index Unordered unordered Allows Duplicate member Allows Duplicate member Allows Duplicate member Not allows Duplicate member Not allows Duplicate member Empty string S = “ ” Empty list L = [ ] Empty tuple T = ( ) Empty set S = set{ } Empty Dictionary D = { } String with single character S = “c” List with single Element L = [ “Hello”] Tuple with single Element T = ( “Hello”,) List with single Element S = set { 1 } List with single Element D = { “a”:1} It can store any datatype: int, str, list, tuple, set and dictionary It can store any datatype: int, string, list, tuple, set and dictionary It can store any datatype: int, str and tuple Key can be int, str and tuple Value can be int, str, list, tuple, set and dictionary 5
  • 6. Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".  Syntax: v_name = “User String”  Example: S = “Hello world!” name = “Sharath” can display a string literal with the print() function: print(s) print(name) 6
  • 7. Multiline strings: We can assign a multiline string to a variable by using three quotes: Example: My_self = ‘‘‘Mr. Sharath H A, Asst. Prof., Dept. of ISE, MIT Mysore.’’’ My_self = “ “ “Mr. Sharath H A, Asst. Prof., Dept. of ISE, MIT Mysore.” ” ” 7 OUTPUT: Mr. Sharath H A, Asst. Prof., Dept. of ISE, MIT Mysore.
  • 8. Strings are Arrays: Python does not have a character data type, a single character is simply a string with a length of 1 Square brackets can be used to access elements of the string. Example: a = ‘Hello’ print(a[1]) 8 OUTPUT: e Note: remember that the first character has the position 0
  • 9. Slicing: Specify the start index and the end index, separated by a colon, to return a part of the string Example: a = ‘Hello World!’ print(a[1:5]) Slicing from the start: By leaving out the start index, the range will start at the first character Example: a = ‘Hello World!’ print(a[:5]) Slice to the end: By leaving out the end index, the range will go to the end Example: a = ‘Hello World!’ print(a[7:]) 9 OUTPUT: ello OUTPUT: Hello OUTPUT: World!
  • 10. Negative Indexing: Use negative indexes to start the slice from the end of the string Example: a = ‘Hello World!’ print(a[-6:-2]) Slicing from the start: By leaving out the start index, the range will start at the first character Example: a = ‘Hello World!’ print([:-2]) Slice to the end: By leaving out the end index, the range will go to the end Example: a = ‘Hello World!’ print(a[-6:]) 10 OUTPUT: Worl OUTPUT: Hello Worl OUTPUT: World!
  • 11. Modify Strings: Python has a set of built-in methods that you can use on strings Upper Case - upper() a = "Hello, World!" print(a.upper()) Lower Case-lower() a = "Hello, World!" print(a.lower()) Remove Whitespace – strip() a = " Hello, World! " print(a.strip()) 11 Replace string- replace() a = "Hello, World!" print(a.replace(“Hello”,“Bellow”)) Split String-split() a = "Hello, World!" print(a.split(“,”))
  • 12. String Concatenation: To concatenate, or combine, two strings you can use the + operator Merge variable a with variable b into variable c a = "Hello" b = "World" c = a + b print(c) c = a + " " + b print(c) 12
  • 13. String Format: As we learned in the Python Variables chapter, we cannot combine strings and numbers like this age = 36 txt = "My name is John, I am " + age print(txt) Use the format() method to insert numbers into strings age = 36 txt = "My name is John, and I am {}" print(txt.format(age)) 13
  • 14. String Format: quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) 14