SlideShare a Scribd company logo
List in PYTHON
PROF. SHARATH H A,
ASST. PROF.,
DEPT. OF ISE
MIT MYSORE.
Introduction
What is Data ?
Data are individual facts, statistics, or items of information, often numeric,
that are collected through observation. Wikipedia
What is Data structure?
The data structure name indicates itself that organizing the data in memory.
There are many ways of organizing the data in the memory
Files
Python Data Structure
list
Lists are used to store multiple items in a single variable. Lists in Python can
be created by just placing the sequence of items inside the square brackets[].
Syntax
Listname = [item1, item2, ……,item n]
Example
mylist = ["apple", "banana", "cherry"]
List in Python
List operation
List Items - Data Types
String, int and boolean data types:
Example
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list4 = ["abc", 34, True, 40, "male"]GUESS???
type()-What is the data type of a list?
From Python's perspective, lists are defined as objects with the data
type 'list':
Example
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
OUTPUT: <class 'list'>
Allow Duplicates- Lists allow duplicate values
Since lists are indexed, lists can have items with the same value:
Example
Thislist=["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
OUTPUT: apple, banana, cherry, apple, cherry
List Length-Print the number of items in the list
To determine how many items a list has, use the len() function:
Example
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
OUTPUT: 3
Python List count() Method
The count() method returns the number of elements with the specified value.
Syntax
list.count(value)
Example
Return the number of times the value 9 appears int the list:
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
OUTPUT: 2
Python List index() Method
The index() method returns the position at the first occurrence of the specified
value.
Syntax
list.index(elmnt)
Example
What is the position of the value 32:
fruits = [4, 55, 64, 32, 16, 32]
x = fruits.index(32)
OUTPUT: 3
Access Items-Print the specific item of the list:
List items are indexed and you can access them by referring to the
index number:
Example
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
OUTPUT: banana
Access Items-Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
OUTPUT: cherry
Access Items-Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
OUTPUT:['cherry', 'orange', 'kiwi']
Accessing the list item
Access Items-Check if Item Exists
To determine if a specified item is present in a list use the in keyword:
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
OUTPUT: Yes, 'apple' is in the fruits list
Change List Items
To change the value of a specific item, refer to the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
OUTPUT:[apple, blackcurrant, cherry]
Change List Items- Change a Range of Item Values
To change the value of items within a specific range, define a list with the new
values, and refer to the range of index numbers where you want to insert the new
values:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
OUTPUT:
Guess??
Example
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
OUTPUT:
Change List Items- Insert()
To insert a new list item, without replacing any of the existing values, we can
use the insert() method.
The insert() method inserts an item at the specified index:
Syntax
insert(position, item)
Example
thislist=["apple", "banana", "cherry"]
thislist.insert(2,"watermelon")
print(thislist)
Add List Items- Append Items
To add an item to the end of the list, use the append() method:
Syntax
list.append(elmnt)
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
OUTPUT:['apple', 'banana', 'cherry', 'orange']
Add List Items- Insert Items
To insert a list item at a specified index, use the insert() method.
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
OUTPUT:
GUESS??
Add List Items- Extend List
To append elements from another list to the current list, use
the extend() method.
Syntax
list.extend(iterable)
Example
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
OUTPUT:
Remove List Items-Remove
Specified Item
The remove() method removes the specified item.
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
OUTPUT: [“apple”, “cherry”]
Remove List Items- Remove Specified
Index
The pop() method removes the specified index.
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
OUTPUT:
Remove List Items- Remove Specified
Index(del)
The del keyword also removes the specified index:
Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
OUTPUT:
Guess???
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
thislist = ["apple", "banana", "cherry"]
del thislist
OUTPUT:
OUTPUT:
Remove List Items-Clear the List
The clear() method empties the list. The list still remains, but it has no
content.
Syntax
list.clear()
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
OUTPUT:[ ]
Loop Through a List
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
OUTPUT:
apple
banana
cherry
For-loop
While-loop
Do-while loop
Python - Sort Alphanumerically
List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:
Example
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
OUTPUT:['banana', 'kiwi', 'mango', 'orange', 'pineapple']
Python - Sort numerical
Example
Sort the list numerically:
thislist = [100, 50, 65, 82, 23]
thislist.sort()
print(thislist)
thislist = [10, "mango", "kiwi",95, "pineapple", "banana",40,67]
thislist.sort()
print(thislist)
OUTPUT:[23, 50, 65, 82, 100]
OUTPUT:
GUESS
Python - Sort Descending
To sort descending, use the keyword argument reverse = True:
Example
Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
OUTPUT: ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
Python - Case Insensitive Sort
By default the sort() method is case sensitive, resulting in all capital letters being
sorted before lower case letters:
Example
Case sensitive sorting can give an unexpected result:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)
thislist.sort(key = str.lower)
OUTPUT: ['Kiwi', 'Orange', 'banana', 'cherry']
Python - Reverse Order
The reverse() method reverses the current sorting order of the elements.
Example
Reverse the order of the list items:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
OUTPUT: ['cherry', 'Kiwi', 'Orange', 'banana']
Python - Copy Lists
You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made
in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
OUTPUT: ['apple', 'banana', 'cherry']
Python - Join Lists- Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
OUTPUT: ['a', 'b', 'c', 1, 2, 3]
Cont…
you can use the extend() method, which purpose is to add elements from one
list to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
OUTPUT: ['a', 'b', 'c', 1, 2, 3]
Cont…
Example
Add a list to a list:
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
OUTPUT: ['apple', 'banana', 'cherry', ["Ford", "BMW", "Volvo"]]
Summary
List is a collection which is ordered and changeable. Allows duplicate
members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
List in Python

More Related Content

What's hot

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
AnitaDevi158873
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Python tuple
Python   tuplePython   tuple
Python tuple
Mohammed Sikander
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
Amisha Narsingani
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
narmadhakin
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Python : Functions
Python : FunctionsPython : Functions
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
Sangita Panchal
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
Akhil Kaushik
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
Piyush rai
 
Python Pandas
Python PandasPython Pandas
Python Pandas
Sunil OS
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
Sharath Ankrajegowda
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 

What's hot (20)

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 

Similar to List in Python

Python Lists.pptx
Python Lists.pptxPython Lists.pptx
Python Lists.pptx
adityakumawat625
 
Python Collection datatypes
Python Collection datatypesPython Collection datatypes
Python Collection datatypes
Adheetha O. V
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
Python list
Python listPython list
LIST_tuple.pptx
LIST_tuple.pptxLIST_tuple.pptx
LIST_tuple.pptx
Abhishek Tiwari
 
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
KavineshKumarS
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
Koteswari Kasireddy
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
Prof. Dr. K. Adisesha
 
list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptx
ssuser8f0410
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4
Syed Farjad Zia Zaidi
 
Python PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptxPython PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptx
NeyXmarXd
 
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
Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
Mahmoud Samir Fayed
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
NawalKishore38
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Asst.prof M.Gokilavani
 
cover every basics of python with this..
cover every basics of python with this..cover every basics of python with this..
cover every basics of python with this..
karkimanish411
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
deepalishinkar1
 

Similar to List in Python (20)

Python Lists.pptx
Python Lists.pptxPython Lists.pptx
Python Lists.pptx
 
Python Collection datatypes
Python Collection datatypesPython Collection datatypes
Python Collection datatypes
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
Python list
Python listPython list
Python list
 
LIST_tuple.pptx
LIST_tuple.pptxLIST_tuple.pptx
LIST_tuple.pptx
 
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
Python Lists is a a evry jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj...
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptx
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4
 
Python PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptxPython PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.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
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
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
 
cover every basics of python with this..
cover every basics of python with this..cover every basics of python with this..
cover every basics of python with this..
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 

Recently uploaded

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 

Recently uploaded (20)

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 

List in Python

  • 1. List in PYTHON PROF. SHARATH H A, ASST. PROF., DEPT. OF ISE MIT MYSORE.
  • 2. Introduction What is Data ? Data are individual facts, statistics, or items of information, often numeric, that are collected through observation. Wikipedia What is Data structure? The data structure name indicates itself that organizing the data in memory. There are many ways of organizing the data in the memory
  • 3.
  • 6. list Lists are used to store multiple items in a single variable. Lists in Python can be created by just placing the sequence of items inside the square brackets[]. Syntax Listname = [item1, item2, ……,item n] Example mylist = ["apple", "banana", "cherry"]
  • 9. List Items - Data Types String, int and boolean data types: Example list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, 3] list3 = [True, False, False] list4 = ["abc", 34, True, 40, "male"]GUESS???
  • 10. type()-What is the data type of a list? From Python's perspective, lists are defined as objects with the data type 'list': Example mylist = ["apple", "banana", "cherry"] print(type(mylist)) OUTPUT: <class 'list'>
  • 11. Allow Duplicates- Lists allow duplicate values Since lists are indexed, lists can have items with the same value: Example Thislist=["apple", "banana", "cherry", "apple", "cherry"] print(thislist) OUTPUT: apple, banana, cherry, apple, cherry
  • 12. List Length-Print the number of items in the list To determine how many items a list has, use the len() function: Example thislist = ["apple", "banana", "cherry"] print(len(thislist)) OUTPUT: 3
  • 13. Python List count() Method The count() method returns the number of elements with the specified value. Syntax list.count(value) Example Return the number of times the value 9 appears int the list: points = [1, 4, 2, 9, 7, 8, 9, 3, 1] x = points.count(9) OUTPUT: 2
  • 14. Python List index() Method The index() method returns the position at the first occurrence of the specified value. Syntax list.index(elmnt) Example What is the position of the value 32: fruits = [4, 55, 64, 32, 16, 32] x = fruits.index(32) OUTPUT: 3
  • 15. Access Items-Print the specific item of the list: List items are indexed and you can access them by referring to the index number: Example thislist = ["apple", "banana", "cherry"] print(thislist[1]) OUTPUT: banana
  • 16. Access Items-Negative Indexing Negative indexing means start from the end -1 refers to the last item, -2 refers to the second last item etc. Example Print the last item of the list: thislist = ["apple", "banana", "cherry"] print(thislist[-1]) OUTPUT: cherry
  • 17. Access Items-Range of Indexes You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items. Example Return the third, fourth, and fifth item: thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(thislist[2:5]) OUTPUT:['cherry', 'orange', 'kiwi']
  • 19. Access Items-Check if Item Exists To determine if a specified item is present in a list use the in keyword: Example Check if "apple" is present in the list: thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list") OUTPUT: Yes, 'apple' is in the fruits list
  • 20. Change List Items To change the value of a specific item, refer to the index number: Example Change the second item: thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) OUTPUT:[apple, blackcurrant, cherry]
  • 21. Change List Items- Change a Range of Item Values To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values: Example Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon": thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"] thislist[1:3] = ["blackcurrant", "watermelon"] print(thislist) OUTPUT:
  • 22. Guess?? Example thislist = ["apple", "banana", "cherry"] thislist[1:3] = ["watermelon"] print(thislist) OUTPUT:
  • 23. Change List Items- Insert() To insert a new list item, without replacing any of the existing values, we can use the insert() method. The insert() method inserts an item at the specified index: Syntax insert(position, item) Example thislist=["apple", "banana", "cherry"] thislist.insert(2,"watermelon") print(thislist)
  • 24. Add List Items- Append Items To add an item to the end of the list, use the append() method: Syntax list.append(elmnt) Example Using the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) OUTPUT:['apple', 'banana', 'cherry', 'orange']
  • 25. Add List Items- Insert Items To insert a list item at a specified index, use the insert() method. Example Insert an item as the second position: thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) OUTPUT: GUESS??
  • 26. Add List Items- Extend List To append elements from another list to the current list, use the extend() method. Syntax list.extend(iterable) Example Add the elements of tropical to thislist: thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) OUTPUT:
  • 27. Remove List Items-Remove Specified Item The remove() method removes the specified item. Example Remove "banana": thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) OUTPUT: [“apple”, “cherry”]
  • 28. Remove List Items- Remove Specified Index The pop() method removes the specified index. Example Remove the second item: thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist) OUTPUT:
  • 29. Remove List Items- Remove Specified Index(del) The del keyword also removes the specified index: Example Remove the first item: thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist) OUTPUT:
  • 30. Guess??? thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist) thislist = ["apple", "banana", "cherry"] del thislist OUTPUT: OUTPUT:
  • 31. Remove List Items-Clear the List The clear() method empties the list. The list still remains, but it has no content. Syntax list.clear() Example Clear the list content: thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) OUTPUT:[ ]
  • 32. Loop Through a List Example Print all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist: print(x) OUTPUT: apple banana cherry For-loop While-loop Do-while loop
  • 33. Python - Sort Alphanumerically List objects have a sort() method that will sort the list alphanumerically, ascending, by default: Example Sort the list alphabetically: thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() print(thislist) OUTPUT:['banana', 'kiwi', 'mango', 'orange', 'pineapple']
  • 34. Python - Sort numerical Example Sort the list numerically: thislist = [100, 50, 65, 82, 23] thislist.sort() print(thislist) thislist = [10, "mango", "kiwi",95, "pineapple", "banana",40,67] thislist.sort() print(thislist) OUTPUT:[23, 50, 65, 82, 100] OUTPUT: GUESS
  • 35. Python - Sort Descending To sort descending, use the keyword argument reverse = True: Example Sort the list descending: thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort(reverse = True) print(thislist) OUTPUT: ['pineapple', 'orange', 'mango', 'kiwi', 'banana']
  • 36. Python - Case Insensitive Sort By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters: Example Case sensitive sorting can give an unexpected result: thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.sort() print(thislist) thislist.sort(key = str.lower) OUTPUT: ['Kiwi', 'Orange', 'banana', 'cherry']
  • 37. Python - Reverse Order The reverse() method reverses the current sorting order of the elements. Example Reverse the order of the list items: thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.reverse() print(thislist) OUTPUT: ['cherry', 'Kiwi', 'Orange', 'banana']
  • 38. Python - Copy Lists You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2. There are ways to make a copy, one way is to use the built-in List method copy(). Example Make a copy of a list with the copy() method: thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) OUTPUT: ['apple', 'banana', 'cherry']
  • 39. Python - Join Lists- Join Two Lists There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator. Example Join two list: list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) OUTPUT: ['a', 'b', 'c', 1, 2, 3]
  • 40. Cont… you can use the extend() method, which purpose is to add elements from one list to another list: Example Use the extend() method to add list2 at the end of list1: list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1) OUTPUT: ['a', 'b', 'c', 1, 2, 3]
  • 41. Cont… Example Add a list to a list: a = ["apple", "banana", "cherry"] b = ["Ford", "BMW", "Volvo"] a.append(b) OUTPUT: ['apple', 'banana', 'cherry', ["Ford", "BMW", "Volvo"]]
  • 42. Summary List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members.