List in Python

A list in Python is an ordered sequence of objects or data. It comprises data items or elements separated by commas and enclosed within a squared bracket.

The syntax for creating a list is shown below:

num = [1,2,3,4,5]

The above is a Python list of five elements with the first element being 1 and the last element being 5.

Lists are heterogenous, meaning that a list can contain objects of various types. For instance, the following list contains numbers, strings and even lists.

#collection of numbers
L = [1,2,3,4,5]
#collection of different data types
L = [1, "color", 2.11, [1,2,3], True,"apple", ["blue", "green"]

An empty list is simply created with two square brackets and nothing in between.

L = []

Operations on a list in Python

Accessing elements in a list

Items in a list can be accessed based on their positions in the list. You can do this by indicating the position of the item on the list, otherwise known as the index.

The index starts from 0 and not 1. This means that the first item in the list has an index of 0, the second item has an index of 1 and so on.

indexes in python list

Since the first element is in the index of 0, the last element will have the index of (N-1). N here means the total number of elements in the list.

If the total number of elements in a list is 10, the last element has an index of 10 – 1, which is 9.

For instance:

fruits = ["apple","orange","mango","grape"]

fruits[0] #fetches the first element

fruits[1] #fetches the second element

fruits[2] #fetches the third element

fruits[3] #fetches the fourth element

You might also access elements in a list by counting backwards from the right.

In this case, the last element in the list has a position of -1, while the second to the last element has a position of -2.


fruits[-4] #fetches the first element

fruits[-3] #fetches the second element

fruits[-2] #fetches the third element

fruits[-1] #fetches the fourth element

Accessing elements starting from the last item in the list is ideal especially if you don’t know the number of items in the list.

Slicing a list

Slicing means selecting a specific item or group of items in a list. It enables you can fetch a given item or sequence of items in a list.

To slice a list, you have to use the slice operator [], specifying the indexes of the first and the last items that you want to fetch.

Fetching sequence of items in a list

Apart from accessing or fetching individual elements in a list using their indices in the list, you might as well want to fetch a group of elements or items in the list.

To do this, you are required to provide the start and the end indexes for the slicing operation.

For example:

fruits[0:2]  – fetches elements from position 0 to but not including the element in position 2.

The general syntax for slicing is [start:stop:step].

The start is the position where to start slicing from.

The stop is where the slicing will stop, excluding the element in the stop position.

Step indicates the number of steps or jumps during the slicing.

However, there are other variants of this general syntax as shown below:

[start]

[start:stop]

To illustrate the above:

L = [1,2,3,4,5]

L[0] is same as L[0:1:1]

L[0:1] is same as L[0:1:1]

Counting in steps

If you don’t want to return all the elements during slicing, you might as well use do slicing using this syntax [start:stop:step].


L = [1,2,3,4,5,6,7,8,9,10]

L[0:9:2]

#output
#[1, 3, 5, 7, 9]

A typical application of step in the slicing operation is for extracting the even or odd numbers in a list of natural numbers.

#Get Even numbers

L[1::2]
#output - [2, 4, 6, 8, 10]

#Get Odd numbers

L[0::2]
#output - [1, 3, 5, 7, 9]

Mutability of Lists

Lists are mutable object types. This implies that lists allow in place changes of items.

For instance, in the list below, items can easily be updated or removed.

L = [1,2,3,4]

L[1] = 0

Hence, L then becomes:

[1,0,2,4]

L[0:2] = []

L becomes:

[4]

Concatenation in lists

Concatenation is combining two or more lists to get another list. You can concatenate or add two lists together using the + operator.


L1 = [1,2,3,4]

L2 = [5,6,7,8]

L1 + L2

#output - [1,2,3,4,5,6,7,8]

Finding the length of a list

You can determine the number of elements in a list, using the len() method. For instance:

L = [1,2,3,4,5]
len(L)

#output
#5

len(L1) returns the number of items in the list.

Repetition of lists

You can repeat the elements in a list any number of times using the multiplication (*) operator.


L*2

#output - [1,2,3,4,5,1,2,3,4,5]

Iterating over a list

Since a list is a sequence of items, you can iterate or loop through the items.

The example below uses the for loop to iterate over the items in a list:


L = [1,2,3,4,5]

for item in L:

    print(item)
#outputs
#1
#2
#3
#4
#5

Membership Test

You can determine whether a given item is in a list using the membership operator in. The outcome is True if the item is on the list or False if the item is not on the list.


1 in L

#Output

#True

Nesting Lists

Lists are heterogenous, and as such can contain items of different data types. A list containing other lists is referred to as a nested list.


L = [[1,2,3], [4,5,6], [7,8,9]]

Accessing items in a nested list

The various lists inside of the nested list can be accessed as well as the items they contain using their positions or indexes.

For instance:

L = [[1,2,3], [4,5,6], [7,8,9]]

print(L[1])

#output - [4, 5, 6]

print(L[1][0])

#output - 4
print(L[1][1])
#output - 5

print(L[1][2])
#output - 6

Built-in Methods for working with lists

Python comes with numerous built-in methods for creating and working with lists.

The following are some of these methods.

Append

The append method is used to attach or add items at the end of a list. Using the append method is one of the easiest ways of adding elements to a list, by adding items to the end of a list.

L = [1,2,3]

L.append(4)

#output

#[1, 2, 3, 4]

The append method makes it easy to build lists dynamically, especially when you are unsure of the items that will make up the list.

You can start with an empty list and subsequently build the list by appending items to it as shown below.


L = []

#add an item

L.append(1)

print(L)

#output
#[1]

L.append(2)
print(L)

#output
#[1, 2]

L.append(3)

print(L)

#output
#[1, 2, 3]

 

Extend

This method is used to append or attach items in a list to another list.

For instance:


L1 = [1,2,3]

L2 = [4,5,6]

L1.extend(L2)

print(L1)

#output - [1, 2, 3, 4, 5, 6]

Insert

The insert method is used to add an item to any position in a list. You are required to provide the index of the position where the item will be inserted and the value to be inserted.

The insert method expects two arguments, the first one being the index upon which the item will be added to the list and the second one, being the item to be added to the list.

In other words, the first argument is the index to add the item, while the second argument is the item to insert.


L = [1,2,3]

L.insert(1,7)

print(L)

#output - [1, 7, 2, 3]

Count

The count method is used to determine the number of occurrences of a given item in a list. To use this method, you are required to provide an argument representing the item that you want to count.


L = [1,2,4,2,5,4,2,2,6,7,1]

print(L.count(1))

#output - 2

print(L.count(2))

#output - 4

Index

The index is used to find the index of the first occurrence of an item in a list, starting from the left.


L = [1,2,3,1,2,3]

print(L.index(1))

#output - 0

print(L.index(3))

#output - 2

Pop

The pop method removes the last item in the list and returns the item.


L = [1,2,3,4,5]

value = L.pop()

print(value)

#output - 5

print(L)

#output - [1, 2, 3, 4]

value = L.pop()

print(value)

#output - 4

print(L)

#output - [1, 2, 3]

This method is very useful especially if you want to remove an item from a list and use the item removed for something else.  You may even wish to store the item in another list.


L1 = [1,2,3,4,5]

L2 = []

L2.append(L1.pop())

print(L2)

#output
#[5]

L2.append(L1.pop())

print(L2)

#output
#[5, 4]

You can also use the pop method to remove an item from a list by specifying the index of the item to be removed.

L = [1,2,3,4,5]

num = L.pop(0)

print(num)

#item removed 
#1

print(L)

#list after removing an item
#[2, 3, 4, 5]

Remove

Like the insert, the remove method is used to remove the first occurrence of a specific value from a list. You can use this method if you are not sure of the index or position of the item that you want to remove. The argument expected from this method is the value of the item to be removed as shown below:


L = [1,2,3,2,4,5] 

L.remove(2) 

print(L) 

#output - [1, 3, 2, 4, 5]

Sort

This method is used to arrange items in a list in ascending or descending order.

The sort method changes the order of a list permanently.

It takes one optional argument which is the reverse. The default for this value is False.

However, changing the reverse from False to True sorts the items in descending order.


L = [6,2,3,1,2]

L.sort()

print(L)

#output - [1, 2, 2, 3, 6]

L.sort(reverse=True)

print(L)

#output - [6, 3, 2, 2, 1]

Reverse

The reverse method is used to reverse the arrangement of the items in a list. It rearranges the items in a list starting from the right end of the list.

sort vs reverse in list in python

Unlike the sort, which permanently arranges a list in ascending or descending order, the reverse only alternates the items from left to right or right to left.


L = [1,2,3,4,5] 

L.reverse() 

print(L) 

#output - [5, 4, 3, 2, 1]

L.reverse() 

print(L) 

#output - [1, 2, 3, 4, 5]

Sorted

The sorted method is used to temporarily present a list in either ascending or descending order.

L = ['orange', 'apple', 'grape', 'pineapple']
print(sorted(L))

#sorted list
#['apple', 'grape', 'orange', 'pineapple']
print(L)

#the list remains unchanged
#['orange', 'apple', 'grape', 'pineapple']

Copy

This method returns a copy of a given list. For instance:


L2 = L.copy()

print(L2)

#output - [1,2,3,4,5]

The above expression is the same thing as:

 

L2 = L[:]

L = [1, 2, 3, 4, 5]

L2 = L.copy()

print(L2)

#output - [1, 2, 3, 4, 5]

Min and Max

The min and max methods are used to determine the smallest and the largest elements in a list.

L = [1, 2, 3, 4, 5]

print(min(L))

#output - 1

print(max(L))

#output - 5

 

Leave a Reply

Your email address will not be published. Required fields are marked *