Lists in Python | Part 2

In this article, we will be learning about accessing elements from a list, removing elements from a list and slicing of lists. This is the second article on lists in Python. To understand more about lists please read the first article called Lists in Python | Part 1.

 

Let us once again define what a list is in the Python language.

 

What are Lists in Python?

Lists are a collection of homogeneous or nonhomogeneous objects. Therefore, the elements of a list need not be of the same datatype. They are the most versatile datatype available in Python. A single list can contain a variety of data types like integers, strings as well as lists themselves.

 

Unlike strings, lists are mutable. Therefore, they can be modified even after creation. Hence, we will be learning to add and remove elements from lists.

 

Accessing elements from Lists in Python:

We can access the elements in a list one at a time with the bracket operator. This is also known as access by the method of indexing. In the indexing method, we pass the index of the element we want inside the square bracket. The index represents the placement of an element in the list. We can access nested lists by using nested indexing (similar to accessing multidimensional arrays).

 

Note: Please keep in mind like any other sequence the index starts from 0 and not 1. In addition, the indexes are always integers.

 

The Python language also has negative indexes, unlike other programming languages. The negative indexes start from the end of a sequence, unlike the positive indexes. The negative indexes start from -1 and keep going into the negatives.

 

Therefore, we can also use negative indexes to access the elements. Passing -1 in the bracket will allow you to access the last element of the list.

The below code snippet shows accessing elements from a list:
# Creating a list
list1 = ['A', 'B', 'C', 'D', 'E']
print(list1)

print()

# accessing elements from list using indexing
a = list1[0]
b = list1[3]
print(a)
print(b)

print()

# accessing elements from list using negative indexing
a = list1[-1]
b = list1[-2]
print(a)
print(b)

# accessing elements from list using nested indexing
list1 = [['Hello', 'World'], ['Program']]
a = list1[0][0]
b = list1[0][1]
c = list1[1][0]
print(a + ' ' + b + ' ' + c)
Output:
['A', 'B', 'C', 'D', 'E']

A
D

E
D

Hello World Program

 

Removing an element from a list:

There are two built-in methods, which we can use to delete elements from a list. Both methods can remove only one element at a time. To remove multiple elements we can use a simple for loop.

The two methods are discussed below:

1. remove(): The remove() method only removes one element at a time. We pass the element that we need to remove as a parameter to the method. The remove() method deletes the first occurrence of the passed value. However, if more than one occurrence of that value is present then the second occurrence is not deleted.

 

Syntax:
List_name.remove(value)

 

The below code snippet shows the working of remove() method:
# creating a list
list1 = ['A', 'B', 'C', 'D', 'E']
print(list1)

print()

# removing element from a list
list1.remove('A')
print(list1)

print()

# removing multiple elements
list1 = ['A', 'B', 'C', 'D', 'E']
for i in range(0, 2):
    list1.remove(list1[i])

print(list1)
Output:
['A', 'B', 'C', 'D', 'E']

['B', 'C', 'D', 'E']

['B', 'D', 'E']

 

2. pop(): The pop method by default removes the last element from the list. If we want to remove a particular element we can pass the index of the element as a parameter to the pop() method. The pop() method also returns the deleted element. Hence, we can use the pop() method to retrieve the deleted element.

Note: The remove() method does not return the deleted element.

 

Syntax:
list_name.pop()
     (or)
list_name.pop(index)

 

The below code snippet shows the working of the pop() method:
# creating a list
list1 = ['A', 'B', 'C', 'D', 'E']
print(list1)

print()

# removing element from a list
list1.pop()
print(list1)

print()

# removing element from a list using index
list1.pop(1)
print(list1)
Output:
['A', 'B', 'C', 'D', 'E']

['A', 'B', 'C', 'D']

['A', 'C', 'D']

 

Slicing a list in Python:

We can access a part of a list in python using slicing. This allows us to access a range of elements in a list. Therefore, we can access multiple elements without using iteration. This helps us to keep our code clean and reduces execution times. The syntax shows the method of slicing a list.

 

Syntax:
list_name[start_index : end_index]

 

In the above syntax, the start_index is inclusive and the end_index is exclusive. Meaning, the start_index is considered as the part of the slice whereas the end_index is not. Therefore, if you want to want a list slice from index 1-10 the end_index should be 11. If we want a list slice from the beginning of a list to a given index the start_index is left blank. Similarly, if we want a slice from in between the list to the end of the list the start_index is passed and the end_index is left blank. We can also use negative indexes to slice the list.

 

The below code snippet depicts slicing of a list:
# creating a list
list1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
print(list1)

print()

# slicing a list from start to given index
list2 = list1[:5]
print(list2)

print()

# slicing a list between two indexes
list2 = list1[2:5]
print(list2)

print()

# slicing a list from a given index to the end
list2 = list1[2:]
print(list2)

print()

# slicing the list from end to start using negative indexes
list2 = list1[::-1]
print(list2)
Output:
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

['A', 'B', 'C', 'D', 'E']

['C', 'D', 'E']

['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

['J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A']

 

To get a list of all the built-in methods that the Python language supports with respect to a list we can declare a list and use the dir() method.

The below code snippet depicts the usage of dir() method:
list = []
a = dir(list)
print(a)
Output:
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', 
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', 
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', 
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 
'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 

This is the end of this article. This is the second part of two posts about lists in python. Please refer to the first article called Lists in Python | Part 1 to learn about creating a list and adding elements to a list.

Leave a Reply

Your email address will not be published.