SlideShare a Scribd company logo
1 of 37
List Creation
List in Python
• In python, a list can be defined as a collection of values or
items.
• The items in the list are separated with the comma (,) and
enclosed with the square brackets [ ].
Syntax:
list_name= [ item1, item2,item3…. ]
Example: “listdemo.py”
L1 = []
L2 = [123,"python", 3.7]
L3 = [1, 2, 3, 4, 5, 6]
L4 = ["C","Java","Python"]
print(L1)
print(L2)
print(L3)
print(L4)
Output:
python listdemo.py
[]
[123, 'python', 3.7]
[1, 2, 3, 4, 5, 6]
['C','Java','Python']
List Operators
List Operators in Python
+
It is known as concatenation operator used to concatenate two
lists.
*
It is known as repetition operator. It concatenates the multiple
copies of the same list.
[]
It is known as slice operator. It is used to access the list item
from list.
[:]
It is known as range slice operator. It is used to access the range
of list items from list.
in
It is known as membership operator. It returns if a particular
item is present in the specified list.
not in
It is also a membership operator and It returns true if a
particular list item is not present in the list.
List Operators in Python cont…
Example: “listopdemo.py”
num=[1,2,3,4,5]
lang=['python','c','java','php']
print(num + lang) #concatenates two lists
print(num * 2) #concatenates same list 2 times
print(lang[2]) # prints 2nd index value
print(lang[1:4]) #prints values from 1st to 3rd index.
print('cpp' in lang) # prints False
print(6 not in num) # prints True
Output: python listopdemo.py
[1, 2, 3, 4, 5, 'python', 'c', 'java', 'php']
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
java
['c', 'java', 'php']
False
True
List Indexing
List Indexing in Python
• Like string sequence, the indexing of the python lists starts from 0,
i.e. the first element of the list is stored at the 0th index, the second
element of the list is stored at the 1st index, and so on.
• The elements of the list can be accessed by using the slice operator
[].
• The syntax for accessing an item in a list is,
• list_name[index]
Example:
mylist=[‘banana’,’apple’,’mango’,’tomato’,’berry’]
• mylist[0]=”banana” mylist[1:3]=[”apple”,”mango”]
• mylist[2]=”mango”
List Indexing in Python cont…
• Unlike other languages, python provides us the flexibility to use
the negative indexing also. The negative indices are counted
from the right.
• The last element (right most) of the list has the index -1, its
adjacent left element is present at the index -2 and so on until
the left most element is encountered.
Example: mylist=[‘banana’,’apple’,’mango’,’tomato’,’berry’]
• mylist[-1]=”berry” mylist[-4:-2]=[“apple”,mango”]
• mylist[-3]=”mango” mvlist[ -3 : ]=[“mango”,”tomato”,’berry’]
Slicing in list
• Slicing of lists is allowed in Python wherein a part of the list
can be extracted by
• specifying index range along with the colon (:) operator which
itself is a list.
• The syntax for list slicing is,
•
• List slicing returns a part of the list from the start index value
to stop index value which includes the start index value but
excludes the stop index value. Step specifies the increment
value to slice by and it is optional.
• 1. >>> fruits = ["grapefruit", "pineapple", "blueberries", "mango",
"banana"]
• 2. >>> fruits[1:3]
• ['pineapple', 'blueberries']
• 3. >>> fruits[:3]
• ['grapefruit', 'pineapple', 'blueberries']
• 4. >>> fruits[2:]
• ['blueberries', 'mango', 'banana']
• 5. >>> fruits[1:4:2]
• ['pineapple', 'mango']
• 6. >>> fruits[:]
• ['grapefruit', 'pineapple', 'blueberries', 'mango', 'banana']
• 7. >>> fruits[::2]
• ['grapefruit', 'blueberries', 'banana']
• 8. >>> fruits[::-1]
• ['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']
• 9. >>> fruits[-3:-1]
• ['blueberries', 'mango']
How to update or change elements to a list?
• Python allows us to modify the list items by using the slice and
assignment operator.
• We can use assignment operator ( = ) to change an item or a
range of items.
Example: “listopdemo1.py”
num=[1,2,3,4,5]
print(num)
num[2]=30
print(num)
num[1:3]=[25,36]
print(num)
num[4]="Python"
print(num)
List1=num1
Print(list1)
Output:
python listopdemo1.py
[1, 2, 3, 4, 5]
[1, 2, 30, 4, 5]
[1, 25, 36, 4, 5]
[1, 25, 36, 4, 'Python']
[1, 25, 36, 4, ‘python’]
Built –in functions used on lists
List Functions & Methods in Python
• Python provides various in-built functions .Those are
☞ len():
• In Python, len() function is used to find the length of list,i.e it
returns the number of items in the list..
Syntax: len(list)
• len()
• any()
• all()
• sum()
• sorted()
Example: listlendemo.py
num=[1,2,3,4,5,6]
print("length of list :",len(num))
Output:
python listlendemo.py
length of list : 6
• ☞ any():
• The any() function returns True if any of the Boolean
values in the list is True.
• Syntax: any(iterable)
• Iterable: It is an iterable object such as a dictionary,
tuple, list, set, etc.
• Ex:
• any([1, 1, 0, 0, 1, 0])
• True
• any(0,0,0,0)
• False
• list2=[1,0,2]
• any(list2)
• True
• ☞ all():
• The all() function returns True if all the Boolean values in the
list are True, else returns False.
• Syntax: any(iterable)
• Iterable: It is an iterable object such as a dictionary, tuple, list,
set, etc.
• Ex:
• >>> all([1, 1, 1, 1])
• True
• >>> all([1,0,2])
• False
• >>> all([1,2,3,4,5,])
• True
List Functions in Python Cont..
☞ sum ():
• In python, sum() function returns sum of all values in the list. List
values must in number type.
Syntax: sum(list)
Example: listsumdemo.py
list1=[1,2,3,4,5,6]
print("Sum of list items :",sum(list1))
Output:
python listsumdemo.py
Sum of list items : 21
List Functions in Python Cont..
☞ sorted ():
• The sorted() function returns a modified copy of the list while
leaving the original list untouched.
Syntax: sorted(list)
Example: sorteddemo.py
num=[23,5,78,9]
print(sorted(num))
[5, 9, 23, 78]
print(num)
[23, 5, 78, 9]
List Methods
List Functions & Methods in Python
• Python provides various methods which can be used with list.
• Those are
• extend
• max()
• min()
• list()
•append()
• remove()
• sort()
• reverse()
• count()
• index()
• insert()
• pop()
• clear()
List Methods in Python Cont..
☞ max ():
• In Python, max() function is used to find maximum value in the list.
Syntax: max(list)
Example: listmaxdemo.py
list1=[1,2,3,4,5,6]
list2=['java','c','python','cpp']
print("Max of list1 :",max(list1))
print("Max of list2 :",max(list2))
Output:
python listmaxdemo.py
Max of list1 : 6
Max of list2 : python
List Methods in Python Cont..
☞ min ():
• In Python, min() function is used to find minimum value in the list.
Syntax: min(list)
Example: listmindemo.py
list1=[1,2,3,4,5,6]
list2=['java','c','python','cpp']
print("Min of list1 :",min(list1))
print("Min of list2 :",min(list2))
Output:
python listmindemo.py
Min of list1 : 1
Min of list2 : c
List Methods in Python Cont..
☞ list ():
• In python, list() is used to convert given sequence (string or tuple)
into list.
Syntax: list(sequence)
Example: listdemo.py
str="python"
list1=list(str)
print(list1)
Output:
python listdemo.py
['p', 'y', 't', 'h', 'o', 'n']
List Methods in Python Cont..
☞ append ():
The append() method adds a single item to the end of the list. This
method does not return new list and it just modifies the original.
Syntax: list.append(item)
where item may be number, string, list and etc.
Example: num=[1,2,3,4,5]
lang=['python','java']
num.append(6)
print(num)
lang.append("cpp")
print(lang)
list=[1,2,3,4]
list.append([6,7])
print(list)
Output:
python appenddemo.py
[1, 2, 3, 4, 5, 6]
['python', 'java', 'cpp']
[1, 2, 3, 4, [6, 7]]
List Methods in Python Cont..
☞ remove ():
• In python, remove() method removes item from the list. It removes
first occurrence of item if list contains duplicate items. It throws an
“value error” if the item is not present in the list.
Syntax: list.remove(item)
Example: removedemo.py
list1=[1,2,3,4,5]
list2=['A','B','C','B','D']
list1.remove(2)
print(list1)
list2.remove("B")
print(list2)
list2.remove("E")
print(list2)
Output:
python removedemo.py
[1, 3, 4, 5]
['A', 'C', 'B', 'D']
ValueError: x not in list
List Methods in Python Cont..
☞ sort ():
• In python, sort() method sorts the list elements into descending or
ascending order. By default, list sorts the elements into ascending
order. It takes an optional parameter 'reverse' which sorts the list
into descending order. This method modifies the original list.
Syntax: list.sort()
Example: sortdemo.py
list1=[6,8,2,4,10]
list1.sort()
print("n After Sorting:n")
print(list1)
print("Descending Order:n")
list1.sort(reverse=True)
print(list1)
Output:
python sortdemo.py
After Sorting:
[2, 4, 6, 8 , 10]
Descending Order:
[10, 8, 6, 4 , 2]
List Methods in Python Cont..
☞ reverse ():
• In python, reverse() method reverses elements of the list. i.e. the
last index value of the list will be present at 0th index. This method
modifies the original list and it does not return a new list.
Syntax: list.reverse()
Example: reversedemo.py
list1=[6,8,2,4,10]
list1.reverse()
print("n After reverse:n")
print(list1)
Output:
python reversedemo.py
After reverse:
[10, 4, 2, 8 , 6]
List Methods in Python Cont..
☞ count():
• In python, count() method returns the number of times an element
appears in the list. If the element is not present in the list, it
returns 0.
Syntax: list.count(item)
Example: countdemo.py
num=[1,2,3,4,3,2,2,1,4,5,8]
cnt=num.count(2)
print("Count of 2 is:",cnt)
cnt=num.count(10)
print("Count of 10 is:",cnt) Output:
python countdemo.py
Count of 2 is: 3
Count of 10 is: 0
List Methods in Python Cont..
☞ index():
• In python, index () method returns index of the passed element. If
the element is not present, it raises a ValueError.
• If list contains duplicate elements, it returns index of first
occurred element.
• This method takes two more optional parameters start and end
which are used to search index within a limit.
Syntax: list. index(item [, start[, end]])
Example: indexdemo.py
list1=['p','y','t','o','n','p']
print(list1.index('t'))
Print(list1.index('p'))
Print(list1.index('p',3,10))
Print(list1.index('z')) )
Output:
python indexdemo.py
2
0
5
Value Error
List Methods in Python Cont..
☞ insert():
• In python, the insert() method inserts the item at the given index,
shifting items to the right.
Syntax: list.insert(index,item)
Example: insertdemo.py
num=[10,20,30,40,50]
num.insert(4,60)
print(num)
num.insert(7,70)
print(num)
Output:
python insertdemo.py
[10, 20, 30, 40, 60, 50]
[10, 20, 30, 40, 60, 50, 70]
List Methods in Python Cont..
☞ pop():
• In python, pop() element removes an element present at specified
index from the list.
Syntax: list.pop(index)
Example: popdemo.py
num=[10,20,30,40,50]
num.pop()
print(num)
num.pop(2)
print(num)
num.pop(7)
print(num)
Output:
python popdemo.py
[10, 20, 30, 40]
[10, 20, 40]
IndexError: Out of range
List Methods in Python Cont..
☞ clear():
• In python, clear() method removes all the elements from the list.
It clears the list completely and returns nothing.
Syntax: list.clear()
Example: cleardemo.py
num=[10,20,30,40,50]
num.clear()
print(num)
Output:
python cleardemo.py
[ ]
List Methods in Python Cont..
☞ Extend():
The extend() method adds the items in list2 to the end of the list.
Syntax: list.extend(list2)
Example: cleardemo.py
list=[1,3,2]
list1=[0,5,6]
list.extend(list1)
print(list) Output:
[1, 3, 2, 0, 5, 6]
Iterating a List
• A list can be iterated by using a for - in loop. A simple list
containing four strings can be iterated as follows..
Example: “listopdemo3.py”
lang=['python','c','java','php‘]
print("The list items are n")
for i in lang:
print(i)
Output:
python listopdemo3.py
The list items are
python
c
java
php
How to delete or remove elements from a list?
• Python allows us to delete one or more items in a list by using
the del keyword.
• .The difference between del statement and pop() function is
that the del statement does not return any value while the
pop() function returns a value.
• The del statement can also be used to remove slices from a list
or clear the entire list.
How to delete or remove elements from a list?
Example:
“listopdemo2.py”
num = [1,2,3,4,5]
print(num)
del num[1]
print(num)
del num[1:3]
print(num)
del num[:]
Output:
python listopdemo2.py
[1, 2, 3, 4, 5]
[1, 3, 4, 5]
[1, 5]
[]
Nested list
• A list inside another list is called a nested list and you can get
the behavior of nested lists in Python by storing lists within the
elements of another list.
• You can traverse through the items of nested lists using the for
loop.
• The syntax for nested lists is
Ex: nested_list=[[item1,item2,item3],
[item4,item5,item6],
[item7,item8,item9]]
nested_list[0]= [item1,item2,item3]
nested_list[1]= [item4,item5,item6]
nested_list[2]= [item7,item8,item9]
nested_list[0][1]=[item2]
• list=[]
• list1=[1,2,3]
• list2=[4,5,6]
• list3=[7,8,9]
• list.append(list1)
• list.append(list2)
• list.append(list3)
• list
• [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
• list[0]
• [1, 2, 3]
• list[1]
• [4, 5, 6]
• list[2]
• [7, 8, 9]
• list[0][1]
• 2
• list[1][2]
• 6
• list[2][1]
• 8

More Related Content

Similar to updated_list.pptx

Similar to updated_list.pptx (20)

11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Python_IoT.pptx
Python_IoT.pptxPython_IoT.pptx
Python_IoT.pptx
 
Lists
ListsLists
Lists
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
List in Python
List in PythonList in Python
List in Python
 
Python list
Python listPython list
Python list
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdfupdated_tuple_in_python.pdf
updated_tuple_in_python.pdf
 
PYTHON.pptx
PYTHON.pptxPYTHON.pptx
PYTHON.pptx
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
lists8.pptx of chapter 12 IP Basic Python
lists8.pptx of chapter 12 IP Basic Pythonlists8.pptx of chapter 12 IP Basic Python
lists8.pptx of chapter 12 IP Basic Python
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
 
tupple.pptx
tupple.pptxtupple.pptx
tupple.pptx
 

More from Koteswari Kasireddy

Chapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfChapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfKoteswari Kasireddy
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfKoteswari Kasireddy
 
Relational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxRelational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxKoteswari Kasireddy
 
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxKoteswari Kasireddy
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxKoteswari Kasireddy
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptxKoteswari Kasireddy
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxKoteswari Kasireddy
 

More from Koteswari Kasireddy (20)

DA Syllabus outline (2).pptx
DA Syllabus outline (2).pptxDA Syllabus outline (2).pptx
DA Syllabus outline (2).pptx
 
Chapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfChapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdf
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
unit-3_Chapter1_RDRA.pdf
unit-3_Chapter1_RDRA.pdfunit-3_Chapter1_RDRA.pdf
unit-3_Chapter1_RDRA.pdf
 
DBMS_UNIT_1.pdf
DBMS_UNIT_1.pdfDBMS_UNIT_1.pdf
DBMS_UNIT_1.pdf
 
business analytics
business analyticsbusiness analytics
business analytics
 
Relational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxRelational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptx
 
CHAPTER -12 it.pptx
CHAPTER -12 it.pptxCHAPTER -12 it.pptx
CHAPTER -12 it.pptx
 
WEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptxWEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptx
 
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptx
 
Evolution Of WEB_students.pptx
Evolution Of WEB_students.pptxEvolution Of WEB_students.pptx
Evolution Of WEB_students.pptx
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Algorithm.pptx
Algorithm.pptxAlgorithm.pptx
Algorithm.pptx
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptx
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
 
linked_list.pptx
linked_list.pptxlinked_list.pptx
linked_list.pptx
 
matrices_and_loops.pptx
matrices_and_loops.pptxmatrices_and_loops.pptx
matrices_and_loops.pptx
 
algorithms_in_linkedlist.pptx
algorithms_in_linkedlist.pptxalgorithms_in_linkedlist.pptx
algorithms_in_linkedlist.pptx
 

Recently uploaded

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

updated_list.pptx

  • 2. List in Python • In python, a list can be defined as a collection of values or items. • The items in the list are separated with the comma (,) and enclosed with the square brackets [ ]. Syntax: list_name= [ item1, item2,item3…. ] Example: “listdemo.py” L1 = [] L2 = [123,"python", 3.7] L3 = [1, 2, 3, 4, 5, 6] L4 = ["C","Java","Python"] print(L1) print(L2) print(L3) print(L4) Output: python listdemo.py [] [123, 'python', 3.7] [1, 2, 3, 4, 5, 6] ['C','Java','Python']
  • 4. List Operators in Python + It is known as concatenation operator used to concatenate two lists. * It is known as repetition operator. It concatenates the multiple copies of the same list. [] It is known as slice operator. It is used to access the list item from list. [:] It is known as range slice operator. It is used to access the range of list items from list. in It is known as membership operator. It returns if a particular item is present in the specified list. not in It is also a membership operator and It returns true if a particular list item is not present in the list.
  • 5. List Operators in Python cont… Example: “listopdemo.py” num=[1,2,3,4,5] lang=['python','c','java','php'] print(num + lang) #concatenates two lists print(num * 2) #concatenates same list 2 times print(lang[2]) # prints 2nd index value print(lang[1:4]) #prints values from 1st to 3rd index. print('cpp' in lang) # prints False print(6 not in num) # prints True Output: python listopdemo.py [1, 2, 3, 4, 5, 'python', 'c', 'java', 'php'] [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] java ['c', 'java', 'php'] False True
  • 7. List Indexing in Python • Like string sequence, the indexing of the python lists starts from 0, i.e. the first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on. • The elements of the list can be accessed by using the slice operator []. • The syntax for accessing an item in a list is, • list_name[index] Example: mylist=[‘banana’,’apple’,’mango’,’tomato’,’berry’] • mylist[0]=”banana” mylist[1:3]=[”apple”,”mango”] • mylist[2]=”mango”
  • 8. List Indexing in Python cont… • Unlike other languages, python provides us the flexibility to use the negative indexing also. The negative indices are counted from the right. • The last element (right most) of the list has the index -1, its adjacent left element is present at the index -2 and so on until the left most element is encountered. Example: mylist=[‘banana’,’apple’,’mango’,’tomato’,’berry’] • mylist[-1]=”berry” mylist[-4:-2]=[“apple”,mango”] • mylist[-3]=”mango” mvlist[ -3 : ]=[“mango”,”tomato”,’berry’]
  • 9. Slicing in list • Slicing of lists is allowed in Python wherein a part of the list can be extracted by • specifying index range along with the colon (:) operator which itself is a list. • The syntax for list slicing is, • • List slicing returns a part of the list from the start index value to stop index value which includes the start index value but excludes the stop index value. Step specifies the increment value to slice by and it is optional.
  • 10. • 1. >>> fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"] • 2. >>> fruits[1:3] • ['pineapple', 'blueberries'] • 3. >>> fruits[:3] • ['grapefruit', 'pineapple', 'blueberries'] • 4. >>> fruits[2:] • ['blueberries', 'mango', 'banana'] • 5. >>> fruits[1:4:2] • ['pineapple', 'mango'] • 6. >>> fruits[:] • ['grapefruit', 'pineapple', 'blueberries', 'mango', 'banana'] • 7. >>> fruits[::2] • ['grapefruit', 'blueberries', 'banana'] • 8. >>> fruits[::-1] • ['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit'] • 9. >>> fruits[-3:-1] • ['blueberries', 'mango']
  • 11. How to update or change elements to a list? • Python allows us to modify the list items by using the slice and assignment operator. • We can use assignment operator ( = ) to change an item or a range of items. Example: “listopdemo1.py” num=[1,2,3,4,5] print(num) num[2]=30 print(num) num[1:3]=[25,36] print(num) num[4]="Python" print(num) List1=num1 Print(list1) Output: python listopdemo1.py [1, 2, 3, 4, 5] [1, 2, 30, 4, 5] [1, 25, 36, 4, 5] [1, 25, 36, 4, 'Python'] [1, 25, 36, 4, ‘python’]
  • 12. Built –in functions used on lists
  • 13. List Functions & Methods in Python • Python provides various in-built functions .Those are ☞ len(): • In Python, len() function is used to find the length of list,i.e it returns the number of items in the list.. Syntax: len(list) • len() • any() • all() • sum() • sorted() Example: listlendemo.py num=[1,2,3,4,5,6] print("length of list :",len(num)) Output: python listlendemo.py length of list : 6
  • 14. • ☞ any(): • The any() function returns True if any of the Boolean values in the list is True. • Syntax: any(iterable) • Iterable: It is an iterable object such as a dictionary, tuple, list, set, etc. • Ex: • any([1, 1, 0, 0, 1, 0]) • True • any(0,0,0,0) • False • list2=[1,0,2] • any(list2) • True
  • 15. • ☞ all(): • The all() function returns True if all the Boolean values in the list are True, else returns False. • Syntax: any(iterable) • Iterable: It is an iterable object such as a dictionary, tuple, list, set, etc. • Ex: • >>> all([1, 1, 1, 1]) • True • >>> all([1,0,2]) • False • >>> all([1,2,3,4,5,]) • True
  • 16. List Functions in Python Cont.. ☞ sum (): • In python, sum() function returns sum of all values in the list. List values must in number type. Syntax: sum(list) Example: listsumdemo.py list1=[1,2,3,4,5,6] print("Sum of list items :",sum(list1)) Output: python listsumdemo.py Sum of list items : 21
  • 17. List Functions in Python Cont.. ☞ sorted (): • The sorted() function returns a modified copy of the list while leaving the original list untouched. Syntax: sorted(list) Example: sorteddemo.py num=[23,5,78,9] print(sorted(num)) [5, 9, 23, 78] print(num) [23, 5, 78, 9]
  • 19. List Functions & Methods in Python • Python provides various methods which can be used with list. • Those are • extend • max() • min() • list() •append() • remove() • sort() • reverse() • count() • index() • insert() • pop() • clear()
  • 20. List Methods in Python Cont.. ☞ max (): • In Python, max() function is used to find maximum value in the list. Syntax: max(list) Example: listmaxdemo.py list1=[1,2,3,4,5,6] list2=['java','c','python','cpp'] print("Max of list1 :",max(list1)) print("Max of list2 :",max(list2)) Output: python listmaxdemo.py Max of list1 : 6 Max of list2 : python
  • 21. List Methods in Python Cont.. ☞ min (): • In Python, min() function is used to find minimum value in the list. Syntax: min(list) Example: listmindemo.py list1=[1,2,3,4,5,6] list2=['java','c','python','cpp'] print("Min of list1 :",min(list1)) print("Min of list2 :",min(list2)) Output: python listmindemo.py Min of list1 : 1 Min of list2 : c
  • 22. List Methods in Python Cont.. ☞ list (): • In python, list() is used to convert given sequence (string or tuple) into list. Syntax: list(sequence) Example: listdemo.py str="python" list1=list(str) print(list1) Output: python listdemo.py ['p', 'y', 't', 'h', 'o', 'n']
  • 23. List Methods in Python Cont.. ☞ append (): The append() method adds a single item to the end of the list. This method does not return new list and it just modifies the original. Syntax: list.append(item) where item may be number, string, list and etc. Example: num=[1,2,3,4,5] lang=['python','java'] num.append(6) print(num) lang.append("cpp") print(lang) list=[1,2,3,4] list.append([6,7]) print(list) Output: python appenddemo.py [1, 2, 3, 4, 5, 6] ['python', 'java', 'cpp'] [1, 2, 3, 4, [6, 7]]
  • 24. List Methods in Python Cont.. ☞ remove (): • In python, remove() method removes item from the list. It removes first occurrence of item if list contains duplicate items. It throws an “value error” if the item is not present in the list. Syntax: list.remove(item) Example: removedemo.py list1=[1,2,3,4,5] list2=['A','B','C','B','D'] list1.remove(2) print(list1) list2.remove("B") print(list2) list2.remove("E") print(list2) Output: python removedemo.py [1, 3, 4, 5] ['A', 'C', 'B', 'D'] ValueError: x not in list
  • 25. List Methods in Python Cont.. ☞ sort (): • In python, sort() method sorts the list elements into descending or ascending order. By default, list sorts the elements into ascending order. It takes an optional parameter 'reverse' which sorts the list into descending order. This method modifies the original list. Syntax: list.sort() Example: sortdemo.py list1=[6,8,2,4,10] list1.sort() print("n After Sorting:n") print(list1) print("Descending Order:n") list1.sort(reverse=True) print(list1) Output: python sortdemo.py After Sorting: [2, 4, 6, 8 , 10] Descending Order: [10, 8, 6, 4 , 2]
  • 26. List Methods in Python Cont.. ☞ reverse (): • In python, reverse() method reverses elements of the list. i.e. the last index value of the list will be present at 0th index. This method modifies the original list and it does not return a new list. Syntax: list.reverse() Example: reversedemo.py list1=[6,8,2,4,10] list1.reverse() print("n After reverse:n") print(list1) Output: python reversedemo.py After reverse: [10, 4, 2, 8 , 6]
  • 27. List Methods in Python Cont.. ☞ count(): • In python, count() method returns the number of times an element appears in the list. If the element is not present in the list, it returns 0. Syntax: list.count(item) Example: countdemo.py num=[1,2,3,4,3,2,2,1,4,5,8] cnt=num.count(2) print("Count of 2 is:",cnt) cnt=num.count(10) print("Count of 10 is:",cnt) Output: python countdemo.py Count of 2 is: 3 Count of 10 is: 0
  • 28. List Methods in Python Cont.. ☞ index(): • In python, index () method returns index of the passed element. If the element is not present, it raises a ValueError. • If list contains duplicate elements, it returns index of first occurred element. • This method takes two more optional parameters start and end which are used to search index within a limit. Syntax: list. index(item [, start[, end]]) Example: indexdemo.py list1=['p','y','t','o','n','p'] print(list1.index('t')) Print(list1.index('p')) Print(list1.index('p',3,10)) Print(list1.index('z')) ) Output: python indexdemo.py 2 0 5 Value Error
  • 29. List Methods in Python Cont.. ☞ insert(): • In python, the insert() method inserts the item at the given index, shifting items to the right. Syntax: list.insert(index,item) Example: insertdemo.py num=[10,20,30,40,50] num.insert(4,60) print(num) num.insert(7,70) print(num) Output: python insertdemo.py [10, 20, 30, 40, 60, 50] [10, 20, 30, 40, 60, 50, 70]
  • 30. List Methods in Python Cont.. ☞ pop(): • In python, pop() element removes an element present at specified index from the list. Syntax: list.pop(index) Example: popdemo.py num=[10,20,30,40,50] num.pop() print(num) num.pop(2) print(num) num.pop(7) print(num) Output: python popdemo.py [10, 20, 30, 40] [10, 20, 40] IndexError: Out of range
  • 31. List Methods in Python Cont.. ☞ clear(): • In python, clear() method removes all the elements from the list. It clears the list completely and returns nothing. Syntax: list.clear() Example: cleardemo.py num=[10,20,30,40,50] num.clear() print(num) Output: python cleardemo.py [ ]
  • 32. List Methods in Python Cont.. ☞ Extend(): The extend() method adds the items in list2 to the end of the list. Syntax: list.extend(list2) Example: cleardemo.py list=[1,3,2] list1=[0,5,6] list.extend(list1) print(list) Output: [1, 3, 2, 0, 5, 6]
  • 33. Iterating a List • A list can be iterated by using a for - in loop. A simple list containing four strings can be iterated as follows.. Example: “listopdemo3.py” lang=['python','c','java','php‘] print("The list items are n") for i in lang: print(i) Output: python listopdemo3.py The list items are python c java php
  • 34. How to delete or remove elements from a list? • Python allows us to delete one or more items in a list by using the del keyword. • .The difference between del statement and pop() function is that the del statement does not return any value while the pop() function returns a value. • The del statement can also be used to remove slices from a list or clear the entire list.
  • 35. How to delete or remove elements from a list? Example: “listopdemo2.py” num = [1,2,3,4,5] print(num) del num[1] print(num) del num[1:3] print(num) del num[:] Output: python listopdemo2.py [1, 2, 3, 4, 5] [1, 3, 4, 5] [1, 5] []
  • 36. Nested list • A list inside another list is called a nested list and you can get the behavior of nested lists in Python by storing lists within the elements of another list. • You can traverse through the items of nested lists using the for loop. • The syntax for nested lists is Ex: nested_list=[[item1,item2,item3], [item4,item5,item6], [item7,item8,item9]] nested_list[0]= [item1,item2,item3] nested_list[1]= [item4,item5,item6] nested_list[2]= [item7,item8,item9] nested_list[0][1]=[item2]
  • 37. • list=[] • list1=[1,2,3] • list2=[4,5,6] • list3=[7,8,9] • list.append(list1) • list.append(list2) • list.append(list3) • list • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] • list[0] • [1, 2, 3] • list[1] • [4, 5, 6] • list[2] • [7, 8, 9] • list[0][1] • 2 • list[1][2] • 6 • list[2][1] • 8