Python
LISTS
Lists
List is one of the built-in data types in Python. A Python list is a sequence of comma separated
items, enclosed in square brackets [ ].
The items in a Python list need not be of the same data type.
Example,
list1 = ["Rohan", "Physics", 21, 69.75]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
list4 = [25.50, True, -55 list, 1+2j]
List is an ordered collection of items. Each item in a list has a unique position index, starting
from 0.
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
For example,
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print (list1[0])
print (list2[1:5])
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator, and you can add to elements in a list with the append() method.
For Example,
list = ['physics', 'chemistry', 1997, 2000];
list[2] = 2001;
print(list);
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know.
For example,
list1 = ['physics', 'chemistry', 1997, 2000];
del list1[2];
print(list1);
Python List Operations
In Python, List is a sequence.
So, we can concatenate two lists with "+" operator and concatenate multiple copies of a list
with "*" operator.
The membership operators "in" and "not in" work with list object.
Python Expression Results Description
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
Python list Methods
Methods Description
list.append(obj) Appends object obj to list.
list.clear() Clears the contents of list.
list.copy() Returns a copy of the list object.
list.count(obj) Returns a copy of the list object.
List.extend(seq) Appends the contents of seq to list.
List.index(obj) Returns the lowest index in list that obj appears.
List.insert(index,obj) Inserts object obj into list at offset index.
List.pop(obj=list[-1]) Removes and returns last object or obj from list.
List.remove(obj) Removes object obj from list.
List.reverse() Reverses objects of list in place.
List.sort([func]) Sorts objects of list, use compare func if given.
Built-in Functions with Lists
Function Description
cmp(list1, list2) Compares elements of both lists.
Len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
list(seq) Converts a tuple into list
Access list items
To access the values within a list, we need to use the square brackets "[]" notation and, specify
the index of the elements we want to retrieve.
The index starts from 0 for the first element and increments by one for each subsequent
element. The index of the last item in the list is always "length-1", where "length" represents the
total number of items in the list.
Accessing List Items with
Indexing
to access the items in a list using indexing, just specify the index of the element with in the
square brackets ("[]").
For example,
list1 = ["Rohan", "Physics", 21, 69.75]
Print(list[2])
Access List Items with Negative
Indexing
Negative indexing in Python is used to access elements from the end of a list, with -1 referring
to the last element, -2 to the second last, and so on.
For example,
list1 = ["a", "b", "c", "d"]
print (list1[-1])
Access List Items with Slice
Operator
The slice operator in Python is used to fetch one or more items from the list. We can access list
items with the slice operator by specifying the range of indices we want to extract. It uses the
following syntax − [start:stop], where start is the starting index (inclusive). stop is the ending
index (exclusive).
If we does not provide any indices, the slice operator defaults to starting from index 0 and
stopping at the last item in the list.
For Example,
list1 = ["a", "b", "c", "d"]
print(list1[1:])
print(list1[:2])
print(list1[:])
print(list1[1:3])
Change list items
List is a mutable data type in Python. It means the contents of the list can be modified in place
after the object is stored in the memory. You can assign a new value at a given index position in
the list.
Syntax: list1[i] = newvalue
Example,
list3 = [1, 2, 3, 4, 5]
list3[2] = 10
Change a Range of List Items,
list1 = ["a", "b", "c", "d"]
list2 = ['X','Y', 'Z’]
list1[1:3] = list2
print (list1)
Add List Items
Adding items in a list typically refers to appending new elements to the end of the list, inserting
them at specific positions within the list, or extending the list with elements from another
iterable object.
We can add list items in Python using various methods such as append(), extend() and insert().
Let us explore all these methods in this tutorial.
Example,
list1 = ["a", "b", "c", "d"]
list1 = ["a", "b", "c", "d"] list1 = ["a", "b", "c", "d"]
list2 = [“e”, ”f”]
list1.append('e’) list1.insert(4, ‘e')
list1.extend(list2)
print (list1) print (list1)
print (list1)
Removing List Items
Removing list items in Python implies deleting elements from an existing list. Lists are ordered
collections of items, and sometimes you need to remove certain elements from them based on
specific criteria or indices.
When we remove list items, we are reducing the size of the list or eliminating specific
elements.
We can remove list items in Python using various methods such as remove(), pop() and clear().
Additionally, we can use the del statement to remove items at a specific index.
Remove List Item Using
remove() Method
The remove() method in Python is used to remove the first occurrence of a specified item from
a list.
We can remove list items using the remove() method by specifying the value we want to
remove within the parentheses, like my_list.remove(value), which deletes the first occurrence of
value from my_list.
Example,
list2 = [25.50, True, -55, 1+2j]
list2.pop(2)
print (list2)
Remove List Item Using pop()
Method
The pop() method in Python is used to removes and returns the last element from a list if no
index is specified, or removes and returns the element at a specified index, altering the original
list.
We can remove list items using the pop() method by calling it without any arguments,
my_list.pop(), which removes and returns the last item from my_list, or by providing the index
of the item we want to remove, my_list.pop(index), which removes and returns the item at that
index.
Example,
list2 = [25.50, True, -55, 1+2j]
list2.pop(2)
print (list2)
Remove List Item Using clear()
Method
The clear() method in Python is used to remove all elements from a list, leaving it empty.
We can remove all list items using the clear() method by calling it on the list object like
my_list.clear(), which empties my_list, leaving it with no elements.
Example,
my_list = [1, 2, 3, 4, 5]
my_list.clear()
print(my_list)
Remove List Item Using del
Keyword
The del keyword in Python is used to delete an element either at a specific index or a slice of
indices from memory.
We can remove list items using the del keyword by specifying the index or slice of the items we
want to delete, like del my_list[index] to delete a single item or del my_list[start:stop] to delete
a range of items.
Example,
list1 = ["a", "b", "c", "d"]
del list1[2]
print (list1)
Loop Through List Items
Looping through list items in Python refers to iterating over each element within a list. We do
so to perform the desired operations on each item.
These operations include list modification, conditional operations, string manipulation, data
analysis, etc.
Python provides various methods for looping through list items, with the most common being
the for loop.
We can also use the while loop to iterate through list items, although it requires additional
handling of the loop control variable explicitly i.e. an index.
Loop Through List Items with For
Loop
A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range)
or any other iterable object.
It allows you to execute a block of code repeatedly for each item in the sequence.
In a for loop, you can access each item in a sequence using a variable, allowing you to perform
operations or logic based on that item's value.
We can loop through list items using for loop by iterating over each item in the list.
Syntax,
for item in list:
# Code block to execute
lst = [25, 12, 10, -21, 10, 100]
for num in lst:
print (num, end = ' ')
Loop Through List Items with
While Loop
A while loop in Python is used to repeatedly execute a block of code as long as a specified
condition evaluates to "True".
We can loop through list items using while loop by initializing an index variable, then iterating
through the list using the index variable and incrementing it until reaching the end of the list.
Syntax,
while condition:
# Code block to execute
my_list = [1, 2, 3, 4, 5]
index = 0
while index < len(my_list):
pxrint(my_list[index])
index += 1
Sorting Lists in Python
Sorting a list in Python is a way to arrange the elements of the list in either ascending or
descending order based on a defined criterion, such as numerical or lexicographical order.
This can be achieved by calling the sort() method on the list itself, both modifying the original
list or returning a new sorted list depending on the method used.
Sorting Lists Using sort() Method
Sort() method is used to sort the elements of a list in place. This means that it modifies the
original list and does not return a new list.
Syntax - list_name.sort(key=None, reverse=False)
Where,
list_name is the name of the list to be sorted.
key (optional) is a function that defines the sorting criterion. If provided, it is applied to each element of
the list for sorting. Default is None.
reverse (optional) is a boolean value. If True, the list will be sorted in descending order. If False (default),
the list will be sorted in ascending order.
Sorting Lists Using sort() Method
Example,
list1 = ['physics', 'Biology', 'chemistry', 'maths’]
list1.sort()
print (list1)
Exercise
Python program to find unique numbers in a given list.
L1 = [1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2]
L2 = []
for x in L1:
if x not in L2:
L2.append(x)
print (L2)
Exercise
Python program to find sum of all numbers in a list.
L1 = [1, 9, 1, 6, 3, 4]
ttl = 0
for x in L1:
ttl+=x
print ("Sum of all numbers Using loop:", ttl)
ttl = sum(L1)
print ("Sum of all numbers sum() function:", ttl)
Exercise
Python program to create a list of 5 random integers.
import random
L1 = []
for i in range(5):
x = random.randint(0, 100)
L1.append(x)
print (L1)