SlideShare une entreprise Scribd logo
1  sur  58
Télécharger pour lire hors ligne
List, Dictionaries, Tuples & Regular
expressions
Presented by:
U.Channabasava
Assistant Professor
List
• List is a sequence of values can be of any data type.
• List elements are enclosed with [ and ].
• List are mutable, meaning, their elements can be
changed.
Exemple:
ls1=[10,-4, 25, 13]
ls2=[“Tiger”, “Lion”, “Cheetah”]
ls3=[3.5, ‘Tiger’, 10, [3,4]]
Creating List
• List is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.
• It can have any number of items and they may be of different
types (integer, float, string etc.).
• Two methods are used to create a list
• Without constructor
• Using list constructor
• The elements in the list can be accessed using a numeric index within
square-brackets.
• It is similar to extracting characters in a string.
Lists are Mutable
Accessing elements of a list
• Index operator [] is used to access an item in a list. Index starts from 0.
marks=[90,80,50,70,60]
print(marks[0])
Output:
90
Nested list:
my_list = [“welcome", [8, 4, 6]]
Print(my_list [1][0])
Output:
8
in operator
The in operator applied on lists will results in a Boolean value.
>>> ls=[34, 'hi', [2,3],-5]
>>> 34 in ls
True
>>> -2 in ls
False
Traversing a list
• The most common way to traverse the elements of a list is with a for
loop.
List elements can be accessed with the combination of range() and
len() functions as well
List Operations
• Slicing [::] (i.e) list[start:stop:step]
• Concatenation = +
• Repetition= *
• Membership = in
List Slices
• Similar to strings, the slicing can be applied on lists as well.
List Methods
• There are several built-in methods in list class for various purposes.
• Some of the functions are
• append()
• extend()
• sort()
• reverse()
• count()
• clear()
• insert()
• index()
append()
• This method is used to add a new element at the end of a list.
extend(arg)
• This method takes a list as an argument and all the elements in this
list are added at the end of invoking list.
sort()
• This method is used to sort the contents of the list. By default, the
function will sort the items in ascending order.
• reverse(): This method can be used to reverse the given list.
• count(): This method is used to count number of occurrences of a
particular value within list.
clear(): This method removes all the elements in the list
and makes the list empty.
insert(pos,value): Used to insert a value before a specified
index of the list.
• index( value, start, end): This method is used to get the index
position of a particular value in the list.
Few important points about List Methods
• There is a difference between append() and extend() methods.
• The former adds the argument as it is, whereas the latter enhances
the existing list.
append() extend()
• The sort() function can be applied only when the list contains
elements of compatible types.
• Similarly, when a list contains integers and sub-list, it will be an error.
• Most of the list methods like append(), extend(), sort(),
reverse() etc. modify the list object internally and return
None.
• List can sort for int and float type
Deleting Elements
• Elements can be deleted from a list in different ways.
• Python provides few built-in methods for removing elements as given
below
• pop()
• remove()
• del
• pop(): This method deletes the last element in the list, by default.
element at a particular index position has to be deleted
• remove(): When we don’t know the index, but know the value to be
removed, then this function can be used.
• Note that, this function will remove only the first occurrence of the
specified value, but not all occurrences.
del: This is an operator to be used when more than one item
to be deleted at a time.
• Deleting all odd indexed elements of a list –
Lists and Functions
• The utility functions like max(), min(), sum(), len() etc. can be used on
lists.
• Hence most of the operations will be easy without the usage of loops.
Lists and Strings
• Though both lists and strings are sequences, they are not same.
>>> s="hello"
>>> ls=list(s)
>>> print(ls)
['h', 'e', 'l', 'l', 'o']
• The method list() breaks a string into individual letters and constructs
a list.
• when no argument is provided, the split() function takes the
delimiter as white space.
• If we need a specific delimiter for splitting the lines, we can use
as shown bellow
• There is a method join() which behaves opposite to split() function.
• It takes a list of strings as argument, and joins all the strings into a
single string based on the delimiter provided.
Parsing lines
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Objects and values
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
two variables refer to the same object
>>> a='kssem'
>>> b='kssem'
>>> a is b
True
But when you create two lists, you get two objects:
• Two lists are equivalent, because they have the same elements, but
not identical, because they are not the same object.
Aliasing
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
• The association of a variable with an object is called as reference.
• b is said to be reference of a
>>> b[2]=100
>>> b
[1, 2, 100]
>>> a
[1, 2, 100]
List Arguments
Dictionaries
• A dictionary is a collection of unordered set of key:value pairs with
the requirement that keys are unique in one dictionary.
• The indices can be (almost) any type.
• len(d)
• ‘mango' in d
True
Dictionary as a Set of Counters
“count the frequency of alphabets in a given string”
There are different methods to do it –
• Create 26 variables to represent each alphabet.
• Create a list with 26 elements representing alphabets.
• Create a dictionary with characters as keys and counters as values.
Dictionaries and files
• One of the common uses of a dictionary is to count the occurrence of
words in a file with some written text.
Looping and dictionaries
• If you use a dictionary as the sequence in a for statement, it traverses
the keys of the dictionary.
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
for k in counts:
print(k, counts[k])
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
for key in counts:
if counts[key] > 10 :
print(key, counts[key])
print the keys in alphabetical order
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}
lst = list(counts.keys())
print(lst)
lst.sort()
for key in lst:
print(key, counts[key])
Advanced text parsing
But, soft! what light through yonder window breaks?
It is the east, and Juliet is the sun.
Arise, fair sun, and kill the envious moon,
Who is already sick and pale with grief,
• split function looks for spaces and treats words as tokens separated
by spaces
Ex: “hi how r u”
• we would treat the words “soft!” and “soft” as different words and
create a separate dictionary entry for each word.
• Also since the file has capitalization, we would treat “who” and
“Who” as different words with different counts.
• We can solve both these problems by using the string methods lower,
punctuation and translate.
line.translate(str.maketrans(fromstr, tostr, deletestr))
Tuples
• A tuple is a sequence of values much like a list.
• The values stored in a tuple can be any type, and they are indexed by
integers.
• The important difference is that tuples are immutable.
Ex:
t = 'a', 'b', 'c', 'd', 'e‘
t = ('a', 'b', 'c', 'd', 'e')
>>> t = tuple()
>>> print(t)
()

Contenu connexe

Tendances

Tendances (20)

Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
python Function
python Function python Function
python Function
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Lists
ListsLists
Lists
 
Python set
Python setPython set
Python set
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 

Similaire à List , tuples, dictionaries and regular expressions in python

Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
Out Cast
 
GF_Python_Data_Structures.ppt
GF_Python_Data_Structures.pptGF_Python_Data_Structures.ppt
GF_Python_Data_Structures.ppt
ManishPaul40
 

Similaire à List , tuples, dictionaries and regular expressions in python (20)

Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 
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
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
 
powerpoint 2-13.pptx
powerpoint 2-13.pptxpowerpoint 2-13.pptx
powerpoint 2-13.pptx
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
Module-3.pptx
Module-3.pptxModule-3.pptx
Module-3.pptx
 
Groovy
GroovyGroovy
Groovy
 
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsAn Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List Algorithms
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptx
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
BCA DATA STRUCTURES LINEAR ARRAYS MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES LINEAR ARRAYS MRS.SOWMYA JYOTHIBCA DATA STRUCTURES LINEAR ARRAYS MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES LINEAR ARRAYS MRS.SOWMYA JYOTHI
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Python lists & sets
Python lists & setsPython lists & sets
Python lists & sets
 
Python list manipulation basics in detail.pdf
Python list  manipulation basics in detail.pdfPython list  manipulation basics in detail.pdf
Python list manipulation basics in detail.pdf
 
GF_Python_Data_Structures.ppt
GF_Python_Data_Structures.pptGF_Python_Data_Structures.ppt
GF_Python_Data_Structures.ppt
 
Intro to Lists
Intro to ListsIntro to Lists
Intro to Lists
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 

Dernier

Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
amitlee9823
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
amitlee9823
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
amitlee9823
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
amitlee9823
 
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
amitlee9823
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
amitlee9823
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
amitlee9823
 

Dernier (20)

Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
 
Predicting Loan Approval: A Data Science Project
Predicting Loan Approval: A Data Science ProjectPredicting Loan Approval: A Data Science Project
Predicting Loan Approval: A Data Science Project
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
Week-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interactionWeek-01-2.ppt BBB human Computer interaction
Week-01-2.ppt BBB human Computer interaction
 
Anomaly detection and data imputation within time series
Anomaly detection and data imputation within time seriesAnomaly detection and data imputation within time series
Anomaly detection and data imputation within time series
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
Mg Road Call Girls Service: 🍓 7737669865 🍓 High Profile Model Escorts | Banga...
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 
Invezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signalsInvezz.com - Grow your wealth with trading signals
Invezz.com - Grow your wealth with trading signals
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Bommasandra Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 

List , tuples, dictionaries and regular expressions in python

  • 1. List, Dictionaries, Tuples & Regular expressions Presented by: U.Channabasava Assistant Professor
  • 2. List • List is a sequence of values can be of any data type. • List elements are enclosed with [ and ]. • List are mutable, meaning, their elements can be changed.
  • 3. Exemple: ls1=[10,-4, 25, 13] ls2=[“Tiger”, “Lion”, “Cheetah”] ls3=[3.5, ‘Tiger’, 10, [3,4]]
  • 4. Creating List • List is created by placing all the items (elements) inside a square bracket [ ], separated by commas. • It can have any number of items and they may be of different types (integer, float, string etc.). • Two methods are used to create a list • Without constructor • Using list constructor
  • 5.
  • 6. • The elements in the list can be accessed using a numeric index within square-brackets. • It is similar to extracting characters in a string.
  • 8. Accessing elements of a list • Index operator [] is used to access an item in a list. Index starts from 0. marks=[90,80,50,70,60] print(marks[0]) Output: 90 Nested list: my_list = [“welcome", [8, 4, 6]] Print(my_list [1][0]) Output: 8
  • 9.
  • 10. in operator The in operator applied on lists will results in a Boolean value. >>> ls=[34, 'hi', [2,3],-5] >>> 34 in ls True >>> -2 in ls False
  • 11. Traversing a list • The most common way to traverse the elements of a list is with a for loop.
  • 12. List elements can be accessed with the combination of range() and len() functions as well
  • 13. List Operations • Slicing [::] (i.e) list[start:stop:step] • Concatenation = + • Repetition= * • Membership = in
  • 14.
  • 15. List Slices • Similar to strings, the slicing can be applied on lists as well.
  • 16.
  • 17.
  • 18. List Methods • There are several built-in methods in list class for various purposes. • Some of the functions are • append() • extend() • sort() • reverse() • count() • clear() • insert() • index()
  • 19. append() • This method is used to add a new element at the end of a list.
  • 20. extend(arg) • This method takes a list as an argument and all the elements in this list are added at the end of invoking list.
  • 21. sort() • This method is used to sort the contents of the list. By default, the function will sort the items in ascending order.
  • 22. • reverse(): This method can be used to reverse the given list. • count(): This method is used to count number of occurrences of a particular value within list.
  • 23. clear(): This method removes all the elements in the list and makes the list empty. insert(pos,value): Used to insert a value before a specified index of the list.
  • 24. • index( value, start, end): This method is used to get the index position of a particular value in the list.
  • 25. Few important points about List Methods • There is a difference between append() and extend() methods. • The former adds the argument as it is, whereas the latter enhances the existing list. append() extend()
  • 26. • The sort() function can be applied only when the list contains elements of compatible types. • Similarly, when a list contains integers and sub-list, it will be an error.
  • 27. • Most of the list methods like append(), extend(), sort(), reverse() etc. modify the list object internally and return None. • List can sort for int and float type
  • 28. Deleting Elements • Elements can be deleted from a list in different ways. • Python provides few built-in methods for removing elements as given below • pop() • remove() • del
  • 29. • pop(): This method deletes the last element in the list, by default. element at a particular index position has to be deleted
  • 30. • remove(): When we don’t know the index, but know the value to be removed, then this function can be used. • Note that, this function will remove only the first occurrence of the specified value, but not all occurrences.
  • 31. del: This is an operator to be used when more than one item to be deleted at a time.
  • 32. • Deleting all odd indexed elements of a list –
  • 33. Lists and Functions • The utility functions like max(), min(), sum(), len() etc. can be used on lists. • Hence most of the operations will be easy without the usage of loops.
  • 34.
  • 35. Lists and Strings • Though both lists and strings are sequences, they are not same. >>> s="hello" >>> ls=list(s) >>> print(ls) ['h', 'e', 'l', 'l', 'o'] • The method list() breaks a string into individual letters and constructs a list.
  • 36. • when no argument is provided, the split() function takes the delimiter as white space. • If we need a specific delimiter for splitting the lines, we can use as shown bellow
  • 37. • There is a method join() which behaves opposite to split() function. • It takes a list of strings as argument, and joins all the strings into a single string based on the delimiter provided.
  • 39. Objects and values >>> a = 'banana' >>> b = 'banana' >>> a is b True two variables refer to the same object >>> a='kssem' >>> b='kssem' >>> a is b True
  • 40. But when you create two lists, you get two objects: • Two lists are equivalent, because they have the same elements, but not identical, because they are not the same object.
  • 41. Aliasing >>> a = [1, 2, 3] >>> b = a >>> b is a True • The association of a variable with an object is called as reference. • b is said to be reference of a >>> b[2]=100 >>> b [1, 2, 100] >>> a [1, 2, 100]
  • 43. Dictionaries • A dictionary is a collection of unordered set of key:value pairs with the requirement that keys are unique in one dictionary. • The indices can be (almost) any type.
  • 44.
  • 46. Dictionary as a Set of Counters “count the frequency of alphabets in a given string” There are different methods to do it – • Create 26 variables to represent each alphabet. • Create a list with 26 elements representing alphabets. • Create a dictionary with characters as keys and counters as values.
  • 47.
  • 48.
  • 49. Dictionaries and files • One of the common uses of a dictionary is to count the occurrence of words in a file with some written text.
  • 50.
  • 51. Looping and dictionaries • If you use a dictionary as the sequence in a for statement, it traverses the keys of the dictionary. counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100} for k in counts: print(k, counts[k])
  • 52. counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100} for key in counts: if counts[key] > 10 : print(key, counts[key])
  • 53. print the keys in alphabetical order counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100} lst = list(counts.keys()) print(lst) lst.sort() for key in lst: print(key, counts[key])
  • 54. Advanced text parsing But, soft! what light through yonder window breaks? It is the east, and Juliet is the sun. Arise, fair sun, and kill the envious moon, Who is already sick and pale with grief,
  • 55. • split function looks for spaces and treats words as tokens separated by spaces Ex: “hi how r u” • we would treat the words “soft!” and “soft” as different words and create a separate dictionary entry for each word. • Also since the file has capitalization, we would treat “who” and “Who” as different words with different counts. • We can solve both these problems by using the string methods lower, punctuation and translate.
  • 57. Tuples • A tuple is a sequence of values much like a list. • The values stored in a tuple can be any type, and they are indexed by integers. • The important difference is that tuples are immutable. Ex: t = 'a', 'b', 'c', 'd', 'e‘ t = ('a', 'b', 'c', 'd', 'e')
  • 58. >>> t = tuple() >>> print(t) ()