List in Python
Introduction to List in Python
Features Of List
Benefits Of List
Defining and Initialising List
Basic List Operation.
o Concatenation.
o List Indexing
o Slicing
Accessing Values of List.
Traversing List.
Updating List.
Deleting values in List.
Build in List functions and Methods.
Introduction to List in Python
Python used 4 built-in data types to store collections of data like Tuple, List, Set, and
Dictionary. These all build in types has different qualities and usage.
A list in python is a data structure that allow you to store multiple items in a single
variable.
It is most versatile and commonly used data type.
It can contain elements of different data types such as integer, string or even other list.
A list is created by placing all the items (elements) inside parentheses [ ], separated by
commas.
A list is a collection of objects which is ordered and mutable (changeable).
List are used to store multiple items in a single variable.
An element in a list can be removed or replaced or we can add new elements.
List are iterable so it contains an index and an item from the original iterable.
List can be used + (concatenation) and * (repetition) operators and returns a new list.
Key Features of List:
Ordered : Items in a list maintain their order. New elements are added at the end of the
list.
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 1 of 18
Mutable: You can change the value of specific items or add/remove elements after a list
has been created.
Heterogeneous: List can hold different data types, including Integer, string or oven other
lists.
Indexing: Each items of the list can be accessed using its index.
Benefits of List.
Flexible Data Storage: List allow to store multiple data types together, making it easy
to group related items.
Dynamic Size: List can grow and shrink as needed. It is very useful when number of
elements in a collection are not fixed.
Efficient Access and Modification: You can access or modify elements by their index
with comfort. It provides flexibility in how you work with the data.
Useful Built-in functions: Python provides several useful methods and functions to
manipulate list, such as append(), remove(), sort(), reverse() etc.
Support build in Iteration : Lists can be iterated using loops. Which is essential for
performing repeated operations on the elements.
Versatility : List can store other lists, they can be used to create more complex structure
like matrices or tables.
Defining and Initialising List.
In Python, there are several ways to define and create lists.
Below are some common methods:
Square Brackets ([]) The most common and direct method.
list() Constructor Flexible, allows creating lists from any iterable.
List Comprehension A concise and Pythonic way to create lists based on existing data.
range() with list() Quickly creates lists of sequential numbers.
Nested Lists Allows creation of complex, multi-dimensional lists.
Functions/Iterators Converts outputs of functions into lists.
Repeating Elements Creates lists with repeated elements.
Using Square Brackets ([])
The most common way to create a list is by using square brackets and separating elements
with commas.
Using the list() Constructor
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 2 of 18
The list() function can be used to create a list from other iterable objects like strings, tuples,
or ranges.
Using List Comprehension
List comprehensions provide a concise way to create lists by iterating over an iterable and
applying an expression or condition.
Using range() and list() Together
The range() function generates a sequence of numbers, and this can be converted into a
list using list().
Using a List of Lists (Nested Lists)
You can create a list of lists (nested lists) by directly defining lists as elements of another
list.
Using From Functions or Iterators
You can create a list by directly converting the output of functions or iterators using the list()
constructor.
Create a list from a map object
Create a list from Repeating Elements
You can create a list with repeated elements using the multiplication operator.
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 3 of 18
List can be nested.
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 4 of 18
List can contain other compound objects, including lists, dictionaries, and other tuples.
Hence, lists can be nested inside of other lists.
Basic operations with List.
Accessing Values in List: To access values in list, use the square brackets for slicing
along with the index or indices to obtain the value available at that index.
Updating List : Lists are mutable, which means you can update or change the values
of tuple elements. and we can concatenate 2 list and it returns 3rd list.
Delete List: We can delete the list.
Accessing Values of List.
There are various methods available for accessing values of the list.
o List Elements accessing by Index.
o List Elements accessing by Slicing.
o List Elements accessing by Looping.
List Elements accessing by Index.
Each Element in a list has an index starting from 0 for the first element and starting from -1
from last element.
Indexing a list with two ways.
Positive Indexing: if you provide a positive integer, it fetches that index from the list
counting from the left.
Negative indexing: if you provide a negative integer, It fetches that index from the list
counting from the right.
Example:
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 5 of 18
List Elements accessing by Slicing.
You can access range of elements by specifying a start and end index.
Slicing always return a new list.
To slice a list you need to use the [] index operator.
Example:
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 6 of 18
List Elements accessing by Looping.
You can iterate each value of the list using a for loop.
Example:
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 7 of 18
Traversing List Elements
We can traverse the elements of list in several ways.
Using a for loop
Using for loop with range()
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 8 of 18
Using enumerate()
List Comprehension
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 9 of 18
Using a while loop
Updating List Elements
Updating list means assign a new value to the element with its index number.
There are multiple ways to update elements of list.
o Single Element: Assign new value to the element using its index.
o Multiple element: Assign new value to the range of elements using slicing.
o Conditionally: Assign new value based on condition using loop.
o Using List Comprehension: It is use to apply a transformation to entire list.
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 10 of 18
Deleting List Elements.
You can delete the elements of the list as per need, as follow
o Single Element:
use del keyword to remove element using its index.
Use remove() to delete first occurrence of element in list.
Using pop() to delete specific element of given index and return.
o Multiple element:
using slicing we can delete multiple elements.
Use clear() to delete all elements.
o Example.
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 11 of 18
LIST OPERATIONS
Membership Operation on List,
o Membership operators are used to validate the membership of a value in a
sequence such as strings, lists or tuples.
o Python has two membership operators – “in” and “not in”.
o Membership Operator ( in ):
o The in operator is used to check if an element is present in a sequence or not. It
returns True if element is present, otherwise return False.
o Example to find 100 in List.
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 12 of 18
o Example to find 30 in List
o Membership Operator ( not in ):
o The not in operator is used to check if an element is present in a sequence or not.
It returns True if element is not present, otherwise return False.
Built in List functions.
o len() function :
This function returns the number of elements in a list.
Syntax: len( list )
o max() function :
This function returns the maximum number from list.
Syntax: max( list )
o min() function :
This function returns the minimum number from list.
Syntax: min( list )
o sum() function :
This function returns the sum of all elements of list.
Syntax: sum( list )
o Use of enumerate()
Returns an enumerate object containing index-value pairs from the list,
which can be used in loops.
Syntax: enumerate(list, start=0)
o Use of map()
Applies a function to all items in the list and returns a map object, which
can be converted into a list.
Syntax:map(function, list)
o Use of filter()
Filters elements in the list based on a function that returns True or False
for each item.
Syntax:filter(function, list)
Example of Built-in functions.
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 13 of 18
Built In List Methods…
Lists provide various built-in methods that allow for operations like adding, removing, or
modifying elements.
Below is a detailed explanation of all built-in methods for Python lists, along with syntax
and examples.
Use Of append()
Adds a single element to the end of the list.
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 14 of 18
Syntax: [Link](element)
Use Of extend()
Extends the list by appending elements from an iterable (e.g., another list).
Syntax: [Link](iterable)
Use of insert()
Inserts an element at a specified index in the list.
Syntax: [Link](index, element)
Use of remove()
Removes the first occurrence of the specified element from the list.
It raises ValueError if element is not in a list.
Syntax: [Link](element)
Use of pop()
Removes and returns the element at the specified index.
If no index is specified, it removes the last item.
It raises IndexError, if index is out of range.
Syntax: [Link]([index])
Use Of clear()
Removes all elements from the list.
Syntax: [Link]()
Use of index()
Returns the index of the first occurrence of the specified element in the list.
If the element is not found, it raises a ValueError.
Syntax: [Link](element, [start, [end]])
Use of count()
Returns the number of occurrences of the specified element in the list.
Syntax: [Link](element)
Use Of sort()
Sorts the list in ascending order by default.
You can pass a custom key function to customize the sorting logic.
Use the reverse parameter to sort in descending order.
Syntax: [Link](key=None, reverse=False)
Use of reverse()
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 15 of 18
Reverses the order of the elements in the list.
Syntax: [Link]()
Use of copy()
Returns a shallow copy of the list.
Syntax: [Link]()
Example Of append() and extend()
Example Of remove(), pop() and clear()
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 16 of 18
Example of insert() and count()
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 17 of 18
Example
Subject: Mastering Python - List Collection Print Date: [24/Oct/24], Page 18 of 18