Python Lists
Python Lists
In this article you will learn the different methods of creating a list, adding,
modifying, and deleting elements in the list. Also, learn how to iterate the list
and access the elements in the list in detail. Nested Lists and List
Comprehension are also discussed in detail with examples.
List in Python:
• The list data structure is very flexible It has many unique inbuilt
functionalities like pop (), append (), etc which makes it easier,
where the data keeps changing.
• Also, the list can contain duplicate elements i.e., two or more items
can have the same values.
• Lists are Heterogeneous i.e., different kinds of objects/elements
can be added
• As Lists are mutable it is used in applications where the values of
the items change frequently.
Length of a List
In order to find the number of items present in a list, we can use the len
() function.
my_list = [1, 2, 3]
print(len(my_list))
# output 3
• Using indexing, we can access any item from a list using its index
number
• Using slicing, we can access a range of items from a list
Indexing
The list elements can be accessed using the “indexing” technique. Lists are
ordered collections with unique indexes for each item. We can access the
items in the list using this index number.
Python Positive and Negative indexing
AD
To access the elements in the list from left to right, the index value starts
from zero to (length of the list-1) can be used. For example, if we want to
access the 3rd element, we need to use 2 since the index value starts from 0.
Note:
• As Lists are ordered sequences of items, the index values start from
0 to the Lists length.
• Whenever we try to access an item with an index more than the
Lists length, it will throw the 'Index Error'.
• Similarly, the index values are always an integer. If we give any
other type, then it will throw Type Error.
Example
As seen in the above example we accessed the second element in the list by
passing the index value as 1. Similarly, we passed index 4 to access the 5th
element in the list.
Negative Indexing
The elements in the list can be accessed from right to left by using negative
indexing. The negative value starts from -1 to -length of the list. It indicates
that the list is indexed from the reverse/backward.
As seen in the above example to access the 4th element from the last (right to
left) we pass ‘-4’ in the index value.
List Slicing
• The start_index denotes the index position from where the slicing
should begin and the end_index parameter denotes the index
positions till which the slicing should be done.
• The step allows you to take each nth-element within
a start_index:end_index range.
Example
my_list = [10, 20, 'Jessa', 12.50, 'Emma', 25, 50]
# Extracting a portion of the list from 2nd till 5th element
print(my_list[2:5])
# Output ['Jessa', 12.5, 'Emma']
# Without end_value
# Stating from 3nd item to last item
print(my_list[3:])
# Output [7.5, 'Emma']
Iterating a List
The objects in the list can be iterated over one by one, by using a for a loop.
# iterate a list
for item in my_list:
print(item)
Output
Tom
7.5
Emma
The index value starts from 0 to (length of the list-1). Hence using the function
range () is ideal for this scenario.
Example
# iterate a list
for i in range(0, len(my_list)):
# print each item using index number
print(my_list[i])
Output
Tom
7.5
Emma
The append () method will accept only one parameter and add it at the end of
the list.
Let’s see the example to add the element ‘Emma’ at the end of the list.
AD
# Using append()
my_list.append('Emma')
print(my_list)
# Output [5, 8, 'Tom', 7.5, 'Emma']
Use the insert () method to add the object/item at the specified position in
the list. The insert method accepts two parameters position and object.
insert(index, object)
It will insert the object in the specified index. Let us see this with an example.
my_list = list([5, 8, 'Tom', 7.50])
# Using insert()
# insert 25 at position 2
my_list.insert(2, 25)
print(my_list)
# Output [5, 8, 25, 'Tom', 7.5]
AD
Using extend ()
The extend method will accept the list of elements and add them at the end of
the list. We can even add another list by using this method.
# Using extend()
my_list.extend([25, 75, 100])
print(my_list)
# Output [5, 8, 'Tom', 7.5, 25, 75, 100]
As seen in the above example we have three integer values at once. All the
values get added in the order they were passed and it gets appended at the
end of the list.
Use for loop to iterate and modify all items at once. Let’s see how to modify
each item of a list.
print(my_list)
# Output [4, 16, 36, 64]
Removing elements from a List
The elements from the list can be removed using the following list methods.
method Description
remove(item) To remove the first occurrence of the item from the list.
pop(index) Removes and returns the item at the given index from the list.
clear() To remove all items from the list. The output will be an empty list.
Use the remove() method to remove the first occurrence of the item from the
list.
Example
# remove item 6
my_list.remove(6)
# remove item 8
my_list.remove(8)
print(my_list)
# Output [2, 4, 10, 12]
A
Remove all occurrence of a specific item
print(my_list)
# Output [4, 8, 12]
Use the pop() method to remove the item at the given index. The pop() method
removes and returns the item present at the given index.
Note: It will remove the last time from the list if the index number is not
passed.
Example
Use del keyword along with list slicing to remove the range of items
my_list = list([2, 4, 6, 8, 10, 12])
Use the list’ clear() method to remove all items from the list.
The clear() method truncates the list.
# clear list
my_list.clear()
print(my_list)
# Output []
The index() function will accept the value of the element as a parameter and
returns the first occurrence of the element or returns ValueError if the element
does not exist.
print(my_list.index(8))
# Output 3
# returns error since the element does not exist in the list.
# my_list.index(100)
my_list1 = [1, 2, 3]
my_list2 = [4, 5, 6]
# Using + operator
my_list3 = my_list1 + my_list2
print(my_list3)
# Output [1, 2, 3, 4, 5, 6]
Copying a list
There are two ways by which a copy of a list can be created. Let us see each
one with an example.
Using assignment operator (=)
This is a straightforward way of creating a copy. In this method, the new list
will be a deep copy. The changes that we make in the original list will be
reflected in the new list.
my_list1 = [1, 2, 3]
# Using = operator
new_list = my_list1
# printing the new list
print(new_list)
# Output [1, 2, 3]
As seen in the above example a copy of the list has been created. The changes
made to the original list are reflected in the copied list as well.
Note: When you set list1 = list2, you are making them refer to the
same list object, so when you modify one of them, all references associated
with that object reflect the current state of the object. So don’t use the
assignment operator to copy the dictionary instead use the copy() method.
The copy method can be used to create a copy of a list. This will create a new
list and any changes made in the original list will not reflect in the new list.
This is shallow copying.
my_list1 = [1, 2, 3]
As seen in the above example a copy of the list has been created. The changes
made to the original list are not reflected in the copy.
List operations
We can perform some operations over the list by using certain functions
like sort(), reverse(), clear() etc.
The sort function sorts the elements in the list in ascending order.
mylist = [3,2,1]
mylist.sort()
print(mylist)
Output
[1, 2, 3]
As seen in the above example the items are sorted in the ascending order.
Output
[1, 6, 5, 4, 3]
As seen in the above example the items in the list are printed in the reverse
order here.
The max function returns the maximum value in the list while the min function
returns the minimum value in the list.
mylist = [3, 4, 5, 6, 1]
print(max(mylist)) #returns the maximum number in the list.
print(min(mylist)) #returns the minimum number in the list.
Output
As seen in the above example the max function returns 6 and min function
returns 1.
Using sum()
The sum function returns the sum of all the elements in the list.
mylist = [3, 4, 5, 6, 1]
print(sum(mylist))
Output
19
As seen in the above example the sum function returns the sum of all the
elements in the list.
all()
In the case of all() function, the return value will be true only when all the
values inside the list are true. Let us see the different item values and the
return values.
#empty list
samplelist4 = []
Output
any()
The any() method will return true if there is at least one true value. In the case
of Empty List, it will return false.
Let us see the same possible combination of values for any() function in a list
and its return values.
#empty list
samplelist4 = []
print("any() Empty list ::",any(samplelist4))
Output
Nested List
The list can contain another list (sub-list), which in turn contains another list
and so on. This is termed a nested list.
In order to retrieve the elements of the inner list we need a nested For-Loop.
nestedlist = [[2,4,6,8,10],[1,3,5,7,9]]
Output
10
As we can see in the above output the indexing of the nested lists with the
index value of the outer loop first followed by the inner list. We can print
values of the inner lists through a nested for-loop.
List Comprehension
List comprehension is a simpler method to create a list from an existing list. It
is generally a list of iterables generated with an option to include only the
items which satisfy a condition.
outputList = {expression(variable) for variable in inputList [if variable
condition1][if variable condition2]
inputList = [4,7,11,13,18,20]
#creating a list with square values of only the even numbers
squareList = [var**2 for var in inputList if var%2==0]
print(squareList)
Output
As seen in the above example we have created a new list from an existing
input list in a single statement. The new list now contains only the squares of
the even numbers present in the input list.
We can even create a list when the input is a continuous range of numbers.
AD
Output
l1 = [10, 20, 30, 40, 50] and l2 = [60, 70, 80, 60]
AD
Operation Description
l1 + l2 Concatenate the lists l1 and l2. Creates a new list containing the items from l1 and l2.
List slicing. Get the items from index i up to index j (excluding j) as a List. An
l1[i:j]
example l1[0:2] is [10, 20]
List slicing with step. Returns a List with the items from index i up to index j taking every k-
l1[i:j:k]
example l1[0:4:2] is [10, 30].
l2.count(60) Returns the number of times a particular item (60) appears in a list. The answer is 2.
Operation Description
l1.index(30) Returns the index number of a particular item (30) in a list. The answer is 2.
l1.index(30, 2, Returns the index number of a particular item (30) in a list. But search Returns the item wit
5) maximum value from a list. The answer is 60 only from index number 2 to 5.
min(l1) Returns the item with a minimum value from a list. The answer is 10.
max(l1) Returns the item with maximum value from a list. The answer is 60.
l1.append([2, 5,
Append the nested list at the end
7])
pop(2) Removes and returns the item at index 2 from the list.