SlideShare a Scribd company logo
1 of 23
Lists in Python3
By Lakshmi Sarvani Videla
NOTE: all the contents in this ppt are taken from w3schools
https://www.w3schools.com/python/python_lists.asp
Python Collections (Arrays)
There are four collection data types in the Python programming language:
•List is a collection which is ordered and changeable. Allows
duplicate members.
•Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
•Set is a collection which is unordered and unindexed. No
duplicate members.
•Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.
List
A list is a collection which is ordered and changeable. In Python lists are written with
square brackets.
Create a List:
Example
thislist = ["apple", "banana", "cherry"]
print(thislist)
The list() Constructor
It is also possible to use the list() constructor to make a list.
Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
You access the list items by referring to the index
number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
print(thislist[-1])
+” operator :- This operator is used to concatenate two lists into a single list.
“*” operator :- This operator is used to multiply the list “n” times and return the
single list.
lis = [1, 2, 3]
lis1 = [4, 5, 6]
lis2= lis + lis1
lis3 = lis * 3
print(lis2)
print(lis3)
Output:
list after concatenation is : 1 2 3 4 5 6
list after combining is : 1 2 3 1 2 3 1 2 3
min() :- This function returns the minimum element of list.
max() :- This function returns the maximum element of list.
lis = [2, 1, 3, 5, 4]
print ("The length of list is : ", len(lis))
# using min() to print minimum element of list
print ("The minimum element of list is : ", min(lis))
# using max() to print maximum element of list
print ("The maximum element of list is : ", max(lis))
Change Item Value
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)
Loop Through a List
You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
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")
List Length
To determine how many items a list have, use the len()
method:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Add Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
To add an item at the specified index, use the insert() method:
Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
The extend() method adds the specified list elements (or any iterable) to the end of
the current list.
Syntax
list.extend(iterable)
iterable Required. Any iterable (list, set, tuple, etc.)
Example Add the elements of cars to the fruits list:
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
Example Add a tuple to the fruits list:
fruits = ['apple', 'banana', 'cherry']
points = (1, 4, 5, 9)
fruits.extend(points)
Remove Item
There are several methods to remove items from a list:
1. The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
2. The pop() method removes the specified index, (or the last item if index is not
specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
The del keyword removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist
del[a : b] :- This method deletes all the elements in range starting from index ‘a’ till
‘b’ mentioned in arguments.
The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
The copy() method returns a copy of the specified list.
Example
Copy the fruits list:
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
The sort() method sorts the list ascending by default.
You can also make a function to decide the sorting criteria(s). Syntax
list.sort(reverse=True|False, key=myFunc)
Example
Sort the list alphabetically:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
Example
Sort the list descending:
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
Sort() Sort the list by the length of the values:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
Example: Sort the list by the length of the values and reversed:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
The reverse() method reverses the sorting order
of the elements.
Example
Reverse the order of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
The built-in function reversed() returns a
reversed iterator object. The buil-in
function reversed() returns a reversed iterator object.
The count() method returns the number of elements with the specified value.
Return the number of times the value "cherry" appears int the fruits list:
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
index(ele, beg, end) :- This function returns the index of first occurrence of element after beg and before
end.
lis = [2, 1, 3, 5, 4, 3]
print ("The first occurrence of 3 after 3rd position is : ", lis.index(3, 3, 6))
print ("The number of occurrences of 3 is : ", end="")
print (lis.count(3))
Output:
The first occurrence of 3 after 3rd position is : 5
The number of occurrences of 3 is : 2
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
count() Returns the number of elements with the specified value
index() Returns the index of the first element with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current
list
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Reading list / array elements from user
a=input()
b= []
for x in a.split():
b.append(int(x))
(or)
a=input()
b = [int(x) for x in a.split()]
# sort the characters in a particular word
a=input()
b=list(a)
b.sort()
print(b)
grades = ['A','B','F','A+','O','F','F']
def remove_fails(grade):
return grade ! = 'F'
ans=list(filter(remove_fails,grades))
print(ans)
from random import shuffle
def jumble(word):
anagram=list(word) #converting a string into list ..here each character is a list item
shuffle(anagram)
return ''.join(anagram) # converting list back into string…we cannot use str(anagram) as it will convert as “[‘o’,’e’….]”
words =['beetroot','carrots','potatoes']
'''anagrams=[]
for word in words:
anagrams.append(jumble(word))
print(anagrams)'''
'''ans=[jumble(word) for word in words]
print(ans)'''
ans=list(map(jumble,words))
print(ans)

More Related Content

What's hot (20)

Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
List in Python
List in PythonList in Python
List in Python
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
String in python use of split method
String in python use of split methodString in python use of split method
String in python use of split method
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
 
Python collections
Python collectionsPython collections
Python collections
 
List in Python
List in PythonList in Python
List in Python
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
Linked list
Linked listLinked list
Linked list
 
Linked list
Linked listLinked list
Linked list
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 

Similar to Python Lists Guide - Everything You Need to Know

Python Collection datatypes
Python Collection datatypesPython Collection datatypes
Python Collection datatypesAdheetha O. V
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212Mahmoud Samir Fayed
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 
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
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184Mahmoud Samir Fayed
 
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 202Mahmoud 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 210Mahmoud Samir Fayed
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in pythonCeline George
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge O T
 

Similar to Python Lists Guide - Everything You Need to Know (20)

Python Collection datatypes
Python Collection datatypesPython Collection datatypes
Python Collection datatypes
 
Python Lists.pptx
Python Lists.pptxPython Lists.pptx
Python Lists.pptx
 
LIST_tuple.pptx
LIST_tuple.pptxLIST_tuple.pptx
LIST_tuple.pptx
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
Python list
Python listPython list
Python list
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212
 
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
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
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...
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
 
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
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
 
1. python
1. python1. python
1. python
 
Python cheatsheet for beginners
Python cheatsheet for beginnersPython cheatsheet for beginners
Python cheatsheet for beginners
 

More from Lakshmi Sarvani Videla (20)

Data Science Using Python
Data Science Using PythonData Science Using Python
Data Science Using Python
 
Programs on multithreading
Programs on multithreadingPrograms on multithreading
Programs on multithreading
 
Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
Simple questions on structures concept
Simple questions on structures conceptSimple questions on structures concept
Simple questions on structures concept
 
Errors incompetitiveprogramming
Errors incompetitiveprogrammingErrors incompetitiveprogramming
Errors incompetitiveprogramming
 
Relational Operators in C
Relational Operators in CRelational Operators in C
Relational Operators in C
 
Recursive functions in C
Recursive functions in CRecursive functions in C
Recursive functions in C
 
Function Pointer in C
Function Pointer in CFunction Pointer in C
Function Pointer in C
 
Functions
FunctionsFunctions
Functions
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Singlelinked list
Singlelinked listSinglelinked list
Singlelinked list
 
Graphs
GraphsGraphs
Graphs
 
B trees
B treesB trees
B trees
 
Functions in python3
Functions in python3Functions in python3
Functions in python3
 
Dictionary
DictionaryDictionary
Dictionary
 
Sets
SetsSets
Sets
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structures
 
C programs
C programsC programs
C programs
 

Recently uploaded

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

Python Lists Guide - Everything You Need to Know

  • 1. Lists in Python3 By Lakshmi Sarvani Videla NOTE: all the contents in this ppt are taken from w3schools https://www.w3schools.com/python/python_lists.asp
  • 2. Python Collections (Arrays) There are four collection data types in the Python programming language: •List is a collection which is ordered and changeable. Allows duplicate members. •Tuple is a collection which is ordered and unchangeable. Allows duplicate members. •Set is a collection which is unordered and unindexed. No duplicate members. •Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
  • 3. List A list is a collection which is ordered and changeable. In Python lists are written with square brackets. Create a List: Example thislist = ["apple", "banana", "cherry"] print(thislist) The list() Constructor It is also possible to use the list() constructor to make a list. Example Using the list() constructor to make a List: thislist = list(("apple", "banana", "cherry")) # note the double round-brackets print(thislist)
  • 4. You access the list items by referring to the index number: Example Print the second item of the list: thislist = ["apple", "banana", "cherry"] print(thislist[1]) print(thislist[-1])
  • 5. +” operator :- This operator is used to concatenate two lists into a single list. “*” operator :- This operator is used to multiply the list “n” times and return the single list. lis = [1, 2, 3] lis1 = [4, 5, 6] lis2= lis + lis1 lis3 = lis * 3 print(lis2) print(lis3) Output: list after concatenation is : 1 2 3 4 5 6 list after combining is : 1 2 3 1 2 3 1 2 3
  • 6. min() :- This function returns the minimum element of list. max() :- This function returns the maximum element of list. lis = [2, 1, 3, 5, 4] print ("The length of list is : ", len(lis)) # using min() to print minimum element of list print ("The minimum element of list is : ", min(lis)) # using max() to print maximum element of list print ("The maximum element of list is : ", max(lis))
  • 7. Change Item Value 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)
  • 8. Loop Through a List You can loop through the list items by using a for loop: Example Print all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist: print(x)
  • 9. 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")
  • 10. List Length To determine how many items a list have, use the len() method: Example Print the number of items in the list: thislist = ["apple", "banana", "cherry"] print(len(thislist))
  • 11. Add Items To add an item to the end of the list, use the append() method: Example Using the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) To add an item at the specified index, use the insert() method: Example Insert an item as the second position: thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist)
  • 12. The extend() method adds the specified list elements (or any iterable) to the end of the current list. Syntax list.extend(iterable) iterable Required. Any iterable (list, set, tuple, etc.) Example Add the elements of cars to the fruits list: fruits = ['apple', 'banana', 'cherry'] cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) Example Add a tuple to the fruits list: fruits = ['apple', 'banana', 'cherry'] points = (1, 4, 5, 9) fruits.extend(points)
  • 13. Remove Item There are several methods to remove items from a list: 1. The remove() method removes the specified item: thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) 2. The pop() method removes the specified index, (or the last item if index is not specified): thislist = ["apple", "banana", "cherry"] thislist.pop() print(thislist)
  • 14. The del keyword removes the specified index: thislist = ["apple", "banana", "cherry"] del thislist[0] The del keyword can also delete the list completely: thislist = ["apple", "banana", "cherry"] del thislist del[a : b] :- This method deletes all the elements in range starting from index ‘a’ till ‘b’ mentioned in arguments. The clear() method empties the list: thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist)
  • 15. The copy() method returns a copy of the specified list. Example Copy the fruits list: fruits = ['apple', 'banana', 'cherry', 'orange'] x = fruits.copy()
  • 16. The sort() method sorts the list ascending by default. You can also make a function to decide the sorting criteria(s). Syntax list.sort(reverse=True|False, key=myFunc) Example Sort the list alphabetically: cars = ['Ford', 'BMW', 'Volvo'] cars.sort() Example Sort the list descending: cars = ['Ford', 'BMW', 'Volvo'] cars.sort(reverse=True)
  • 17. Sort() Sort the list by the length of the values: # A function that returns the length of the value: def myFunc(e): return len(e) cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] cars.sort(key=myFunc) Example: Sort the list by the length of the values and reversed: # A function that returns the length of the value: def myFunc(e): return len(e) cars = ['Ford', 'Mitsubishi', 'BMW', 'VW'] cars.sort(reverse=True, key=myFunc)
  • 18. The reverse() method reverses the sorting order of the elements. Example Reverse the order of the fruit list: fruits = ['apple', 'banana', 'cherry'] fruits.reverse() The built-in function reversed() returns a reversed iterator object. The buil-in function reversed() returns a reversed iterator object.
  • 19. The count() method returns the number of elements with the specified value. Return the number of times the value "cherry" appears int the fruits list: fruits = ['apple', 'banana', 'cherry'] x = fruits.count("cherry") index(ele, beg, end) :- This function returns the index of first occurrence of element after beg and before end. lis = [2, 1, 3, 5, 4, 3] print ("The first occurrence of 3 after 3rd position is : ", lis.index(3, 3, 6)) print ("The number of occurrences of 3 is : ", end="") print (lis.count(3)) Output: The first occurrence of 3 after 3rd position is : 5 The number of occurrences of 3 is : 2
  • 20. Python has a set of built-in methods that you can use on lists/arrays. Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the first item with the specified value reverse() Reverses the order of the list sort() Sorts the list count() Returns the number of elements with the specified value index() Returns the index of the first element with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
  • 21. Reading list / array elements from user a=input() b= [] for x in a.split(): b.append(int(x)) (or) a=input() b = [int(x) for x in a.split()]
  • 22. # sort the characters in a particular word a=input() b=list(a) b.sort() print(b) grades = ['A','B','F','A+','O','F','F'] def remove_fails(grade): return grade ! = 'F' ans=list(filter(remove_fails,grades)) print(ans)
  • 23. from random import shuffle def jumble(word): anagram=list(word) #converting a string into list ..here each character is a list item shuffle(anagram) return ''.join(anagram) # converting list back into string…we cannot use str(anagram) as it will convert as “[‘o’,’e’….]” words =['beetroot','carrots','potatoes'] '''anagrams=[] for word in words: anagrams.append(jumble(word)) print(anagrams)''' '''ans=[jumble(word) for word in words] print(ans)''' ans=list(map(jumble,words)) print(ans)