Python Fundamentals – Lists

A list is a generic sequence data structure in python consisting of an ordered collection of objects. The objects in a list are also known as elements or components.

The elements or components of a list need not be the same type. It is quite possible that a list can consist of a numeric array, a logical value, a matrix, a complex vector, a character array or a function, etc. The elements inside the list are enclosed between two square brackets [].

The most important properties of the list are, it is indexable and mutable. Each data element in the list is associated with a unique index value, and these data elements can be changed or modified. So once we created, we can easily modify, append and delete data elements based on the index values from the list.

Operations on List Data Type

A list is an inbuilt data type and supports multiple operations, and these operations are explained with examples and use cases as follows.

Create a new List

There are two ways to create a list object, the first one is we can instantiate and then add elements on it or we can directly add elements with comma separable. The below example, explains how to create and add elements in the list.

# Instantiate list object and then add elements
indian_movie_list = []
indian_movie_list = ['Albela','Zubeidaa', 'Officer', 'Chandni Bar','Censor','Farz']
print(indian_movie_list)

# Instantiate and elements addition simultaneously
indian_movie_list_auto = ['Albela','Zubeidaa', 'Officer', 'Chandni Bar','Censor','Farz']
print(indian_movie_list_auto)

# A list of strings
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list)

# A list of integers
integer_list = [101,201]
print(integer_list)

# List of lists with different data types
mix_list = [indian_movie_list,indian_movie_director_list, 1]
print(mix_list)

# List of lists with different data types
adv_mix_list = [[1,2,3,4,5],['Test A','Test B','Test C'],[0.2,1,3,4,5.0]]
print(adv_mix_list)

Find the length of a List

To know the length of a list, we can use len() function. Mainly, it counts the number of elements from the list irrespective of the data type stored within a list. The below example, explains how to find the list length.

# To find the length of a list
indian_movie_list = ['Albela','Zubeidaa', 'Officer', 'Chandni Bar','Censor','Farz']
print(len(indian_movie_list))

# To find the length of a list
adv_mix_list = [[1,2,3,4,5],['Zubeidaa', 'Officer', 'Chandni Bar'],[0.2,1,3,4,5.0]]
print(len(adv_mix_list))

Append a new data element in a List

To add a new data element at the end of the list, we can use append() function. It appends a new data element at the end of the list. The below example, explains how to add new data element in a existing list.

# A list with movie names
movie_list = ['Albela','Zubeidaa', 'Officer']

# Append a string
movie_list.append("Chandni Bar")
print(movie_list)

# Output
# ['Albela', 'Zubeidaa', 'Officer', 'Chandni Bar']

# Append a list 

latest_list = ['Censor','Farz']
movie_list.append(latest_list)
print(movie_list)

# Output
# ['Albela', 'Zubeidaa', 'Officer', 'Chandni Bar', ['Censor', 'Farz']]

Insert a new element anywhere in a List

We can also add new data elements using a method called insert(). The insert() function is beneficial when we want to add a new data element anywhere in the list. It overcomes the append() function limitation, which only allows adding a new element at the end of the list.

Theinsert() function takes two arguments. The first one is location or index number, and the second one is a data element. The below example, explains how to insert a  new data element anywhere in a existing list.

# A list with movie names
movie_list = ['Albela','Zubeidaa', 'Officer']

# New movie 
new_movie = "Chandni Bar"

# Append at the 0th index
movie_list.insert(0,new_movie)
print(movie_list)

# Output
# ['Chandni Bar', 'Albela', 'Zubeidaa', 'Officer']

# Append at the 2th index
new_movie = "Chandni"
movie_list.insert(2,new_movie)
print(movie_list)

# Output
# ['Chandni Bar', 'Albela', 'Chandni', 'Zubeidaa', 'Officer']

Remove elements from a List

We can also remove elements from the list by specifying the element name. However, if there are mutlple occurances of the same element in a list then it always removes the first occurrence from the list. The below example, illustrates how to remove an element from the existing list.

# Indian movie director name list
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

# Remove an element called 'Deepak Sareen' from the list
indian_movie_director_list.remove('Deepak Sareen')
print(indian_movie_director_list)

# Output
# ['Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

Extend a List

We have seen how to insert or append a new element in a list. However, both these functions append a new element as an object and the new element may be any datatype which may not be completely iterable. Thus, the extend function makes a list iterable till the end. The below example, illustrates how to extend the existing list.

# Indian movie director name list
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']
# Suppose above output is our requirements. 

indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker']
new_directors = ['Pankaj Parashar','K.S. Adiyaman']

# Using append function
indian_movie_director_list.append(new_directors)
print(indian_movie_director_list)

# Output 
# ['Deepak Sareen', 'Ashutosh Gowariker', ['Pankaj Parashar', 'K.S. Adiyaman']]

# The append happens as a list inside another list, but we require to add it as an elements
# For that, we need to use Extend function.

indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker']
new_directors = ['Pankaj Parashar','K.S. Adiyaman']
indian_movie_director_list.extend(new_directors)
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

The is another operator (+) through this operator also, we can extend the list. The below example, illustrates how to extend the existing list using (+) operator.

# Directors list
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker']
new_directors = ['Pankaj Parashar','K.S. Adiyaman']

# Extend using + operator
uploaded_indian_movie_director_list= indian_movie_director_list  +new_directors
print(uploaded_indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

Delete elements from a List

One of the important functionality is to delete elements from the list. This can be done using del() or pop() functions. The major difference between del() and pop() is that the pop() function returns the index element, whereas the del() function does not return anything. Both these functions take index numbers as input. The below example, illustrates how to delete elements from the existing list.

# Indian movie director name list
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list)

# Output 
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

del indian_movie_director_list[1]
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Pankaj Parashar', 'K.S. Adiyaman']

When there is a requirement to delete data elements from the list based on the index value, the del() function is appropriate. However, when we also want to retain the deleted data element, then the pop() function is appropriate. The example of pop function is as mentioned below.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list)

# Output 
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

name = indian_movie_director_list.pop(0)
print(name)

# Output
# Deepak Sareen

# To check the indian_movie_director_list
print(indian_movie_director_list)

# Output
# ['Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

The above delete function work based on the index value, and there are various scenarios where we want to remove or delete elements based on the element name rather than the index value. In that case, we can use remove() function.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list)

# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

# Suppose we want to remove 'Deepak Sareen' from the list.

indian_movie_director_list.remove('Deepak Sareen')
print(indian_movie_director_list)

# Output
# ['Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

The remove()function removes the first occurrence of an element from the list if the supplied element name is valid and exists in the list.  In this way, we have three options to delete data elements from the list, and we can use one of these functions based on our requirements.

Sorting elements from a list

Sorting can be done in multiple ways in python. However, the list data type provides a method called sort()which sorts the entire list in ascending order by default, but it can be changed by setting reverse as True, and the whole data sequence manipulation is done on the same list object.

The sort()function takes two arguments as input; the first one is called reverse and it takes a boolean argument as True or False to sort by order. The second argument is key and through this argument, we can supply our own custom function for sorting. The custom function is very useful when the object type is not symmetric. All these concept will be explained in the later section of this note. The below example, explains how to sort list elements of string type.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

# To sort we will use, sort()
indian_movie_director_list.sort()
print(indian_movie_director_list)

# Output
# ['Ashutosh Gowariker', 'Deepak Sareen', 'K.S. Adiyaman', 'Pankaj Parashar']

# Sort the elements in the descending order
indian_movie_director_list.sort(reverse=True)
print(indian_movie_director_list)

# Output
# ['Pankaj Parashar', 'K.S. Adiyaman', 'Deepak Sareen', 'Ashutosh Gowariker']

In the above code snippets,we have seen how to sort elements of string type. However, in the below code, we will see how to sort elements of numerical type.

# Numerical Data
integer_list = [1,2,5,4,3,8,7,6]
print(integer_list)

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

# To sort we will use, sort()
integer_list.sort(reverse=False)
print(integer_list)

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

There is another sort function available in python called the  sorted(). It mainly does the same thing except, it does not manipulate the original list object. Rather it creates a new list data object and stores sorted data elements. This function is beneficial when we don’t want to manipulate our original list object.

The sorted()function takes two arguments as input; the first one is called input data type and the second argument is called reverse, takes a boolean argument as True or False to sort by order. The below example code, explains how to sort list and stores it into another list object.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

# To sort we will use, sort()
sort_list = sorted(indian_movie_director_list)


print(sort_list)

# Output
# ['Ashutosh Gowariker', 'Deepak Sareen', 'K.S. Adiyaman', 'Pankaj Parashar']

One of the limitations of the existing functions is that they can’t sort a list if it contains different data types. In that case, it returns an error. To handle this condition, the existing function provides a keyword called key a function argument. We can apply our own sorting function through this argument, and sorting logic will be implemented according to our own requirements. In the below example code, we have implemented our own sorting code which sorts both string and interger data objects from the list.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker',6,'Pankaj Parashar','K.S. Adiyaman',1,5,3]
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 6, 'Pankaj Parashar', 'K.S. Adiyaman', 1, 5, 3]

def my_custom_sorting_alg(input_list):
    try:
        temp = int(input_list)
        return (0, temp, '')
    except ValueError:
        return (1, input_list, '')
    
# To sort we will use, sort()
indian_movie_director_list.sort(key=my_custom_sorting_alg)
print(indian_movie_director_list)

# Output 
# [1, 3, 5, 6, 'Ashutosh Gowariker', 'Deepak Sareen', 'K.S. Adiyaman', 'Pankaj Parashar']

Split String object into a List

To split a string into a list based on the split condition is very easy in python. This can be done using the split() function provided by the str class in python. The split() function takes the split condition as an argument and returns a list. The below example code explains, how to split string object into a list.

# Input String
input_str = "Deepak Sareen Ashutosh Gowariker Pankaj Parashar K.S. Adiyaman"


# Print the input string
print(input_str)

# Split the string based on the space
new_list = input_str.split()

# Print new_list list
print(new_list)


# Output
# ['Deepak', 'Sareen', 'Ashutosh', 'Gowariker', 'Pankaj', 'Parashar', 'K.S.', 'Adiyaman']

Accessing list elements using Indexing technique

In a list, each data element is assigned an index number, and through this index number, we can access that data element, and this process is called indexing.

There are two types of indexing, positive and negative. The positive indexing starts from the leftmost element, and zero is the first index. Consider the following list to understand it.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']


# Accessing the index zero element
print(indian_movie_director_list[0])
print(indian_movie_director_list[1])
print(indian_movie_director_list[2])
print(indian_movie_director_list[3])


# Output
# Deepak Sareen
# Ashutosh Gowariker
# Pankaj Parashar
# K.S. Adiyaman

If we iterate from the leftmost to the rightmost, it always starts from 0 to n-1, where the total number of elements in the list is n. However, if we want to access the list elements in the reverse order, then use negative indexing.

Negative indexing always starts from index value -1 and ends to -n, when the total number of elements is n. Consider the below code snippet to understand it.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']


# Accessing the index zero element
print(indian_movie_director_list[-1])
print(indian_movie_director_list[-2])
print(indian_movie_director_list[-3])
print(indian_movie_director_list[-4])


# Output
# K.S. Adiyaman
# Pankaj Parashar
# Ashutosh Gowariker
# Deepak Sareen

Slicing of elements from a list

To access parts of the list, segments are called slicing. It follows the following syntax: [Start:End:Step_Size]. Start tells the index value from where elements to be copied, End tells the index value -1 till there to be copied, and Step_Size tells whether any element needs to be escaped. For example:

  • [0:4:1], start coping from 0th index till 3rd index element without escaping any element in between.
  • [0:4:2], start coping from 1st index till 2nd index element with escaping every alternative element in between.
  • [::2], start coping from the 0th index till the end with escaping every alternative element in between.

In the below example, we try to get elements whose index values lie between zero and three without including three. It fetches zero, first, and second elements from the list and copies them to the new list.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list[:])

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

# Below code will split the list and get the elements from 0 to 2 index value
first_three_dir_names =  indian_movie_director_list[0:3:1]
print(first_three_dir_names)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar']

In the below example, we will try to understand step size. The step size is similar to forloop increment values when we are iterating a list.

# Directors List
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Pankaj Parashar','K.S. Adiyaman']
print(indian_movie_director_list[:])

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Pankaj Parashar', 'K.S. Adiyaman']

# Below code will split the list and get the elements from 0 to 2 index value
first_three_dir_names =  indian_movie_director_list[::2]
print(first_three_dir_names)

# Output
# ['Deepak Sareen', 'Pankaj Parashar']

Count the occurance of an element

Again, this is one of the interesting functions that tell the number of occurrences of an element in the list. The count() function takes input as a data element and returns a count value.  The below example code illustrates how to count occurances of an element from a list.

# Directors list
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Deepak Sareen','Deepak Sareen','K.S. Adiyaman']
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Deepak Sareen', 'Deepak Sareen', 'K.S. Adiyaman']


# Print Count Values

# It should print 3 as this name occurs three times in the list
print(indian_movie_director_list.count('Deepak Sareen'))

# It should print 1
print(indian_movie_director_list.count('Ashutosh Gowariker'))

# It should print 1
print(indian_movie_director_list.count('K.S. Adiyaman'))

# It should print 0 as this name is not exist in the list
print(indian_movie_director_list.count('Pankaj Parashar'))

# Output 
# 3
# 1
# 1
# 0

Looping & iterating a list

Looping provides a mechanism to iterate the entire list. It picks each element one by one till the end of the list. The below example illustrated how it works.

# Directors list
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Deepak Sareen','Deepak Sareen','K.S. Adiyaman']
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Deepak Sareen', 'Deepak Sareen', 'K.S. Adiyaman']


# loop though a list
for data_element in indian_movie_director_list:
    print(data_element)
    
# Output
# Deepak Sareen
# Ashutosh Gowariker
# Deepak Sareen
# Deepak Sareen
# K.S. Adiyaman

List Comprehensions

List comprehensions are simply a way to compress a list-building for-loop into a single and readable line. Its basic syntax is [expression for item in collection]. We will practice few basic list comprehensions with examples. The example code illustrates how to create a new list using list comprehension technique.

# Directors list
indian_movie_director_list = ['Deepak Sareen', 'Ashutosh Gowariker','Deepak Sareen','Deepak Sareen','K.S. Adiyaman']
print(indian_movie_director_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Deepak Sareen', 'Deepak Sareen', 'K.S. Adiyaman']

new_list = [data_element for data_element in indian_movie_director_list]
print(new_list)

# Output
# ['Deepak Sareen', 'Ashutosh Gowariker', 'Deepak Sareen', 'Deepak Sareen', 'K.S. Adiyaman']

This example illustrates how to create a new list with conditions.

# Conditional list Comprehension
numerical_list = [100,200,10,20,40,50,101,400]
print(numerical_list)

# Output
# [100, 200, 10, 20, 40, 50, 101, 400]

# Create a list of values equal to or greater than 100
updated_list = [num for num in numerical_list if num >= 100]
print(updated_list)

# Output
# [100, 200, 101, 400]

Summary

In this note, we have seen various methods provided by the list class to create, access and manipulate a list object. Understand of these methods help a lot when we do real programming or data science assignments.

 87 total views,  1 views today

Scroll to Top
Scroll to Top
%d bloggers like this: