(Python part 6)

Mastering Lists in Python: A Comprehensive Guide

Table of Contents

Introduction:

Hello guys, today we will be continuing our journey through the data types in Python. In our last post, we covered string and numeric  data types in detail. Today, we will be focusing on Lists in Python. We will cover everything you need to know about lists, from what they are, how to create them, and how to work with them. So, let’s dive in and get started!

Lists in python

Lists are like the Swiss Army Knife of Python data types – they’re incredibly versatile and can handle a wide range of tasks.

A list is a collection of ordered and mutable elements.

00

These elements that are contained within a list can be of different data types such as integers, strings, and even other lists. In other words, a list can be thought of as a container that holds a sequence of objects, which can be accessed and manipulated in various ways.

 

Lists provide a flexible and convenient way to store and process data in Python, making them an essential data structure for every Python programmer.

 

What are lists in python?

 

A list is a built-in Python data type that represents a collection of elements. Lists are defined using square brackets [] and each element in the list is separated by a comma. It can contain elements of different data types, such as integers, strings, and even other lists. Lists are mutable, meaning you can add, remove or modify elements after the list has been created. The order of the elements in the list is preserved and can be accessed using an index.

Creating a List

There are multiple ways to create a list in Python. Some of the common methods are:


1. Using square brackets:

The simplest way to create a list is to define it using square brackets. Here’s an example:

01 (4)
2. Using the eval() function: eval()

is a built-in Python function that evaluates a string as a Python expression and returns the result. It takes a single parameter, which is the string to be evaluated.

 

Using eval() function we can create a list as follows.

02

Input: [1,2,3, “banana”, “apple”]

 

In this code, the input() function prompts the user to enter a list of elements as a string enclosed within square brackets []. The string is then passed through eval(), which converts it into a list.

 

3. Using the list() function:

Using the list() function: You can create a list by passing an iterable (such as a tuple, string, or range) to the list() function. Here’s an example:

03
4. Using list comprehension:

List comprehension is a concise way of creating a list by applying an expression to each element of an iterable. Here’s an example:

04

Adding elements to a List

Once a list has been created, you can add new elements to it using various methods. Here are some common ways to add elements to a list in Python:

 

1. Using the append() method:

The append() method is a built-in Python function used to add a single element to the end of a list.

 

Syntax: list.append(item)

  • List: is the name of the list to which you want to add the new item
  • Item: the new element that you want to add.
05

Note: It’s important to note that the append() and all other methods that we will discuss here modifies the original list in place, rather than creating a new list. This means that if you append an item to a list, the original list will be changed permanently.

 

2. Using the extend() method:

The extend() method is used to add multiple elements to the end of a list. It takes an iterable (such as another list) as its argument and adds each element from the iterable to the list. 

 

Syntax: list.extend(iterable)

  • List: is the name of the list to which you want to add the new items.
  • Iterable: any iterable object (e.g., list, tuple, string) containing the new elements that you want to add.
06
3. Using the insert() method:

The insert() method is used to add a single element at a specific index in the list. It takes two arguments: the index where you want to add the element, and the element itself.

 

Syntax: list.insert(index, element)

  • List: name of the list to which you want to add the new element
  • Index: index at which you want to insert the element
  • Element: new element that you want to insert
07

Note: Lists in Python are indexed starting from 0, which means that the first element in a list has an index of 0, the second element has an index of 1, and so on. Negative indexing is also supported by lists, allowing the last element to have an index value of -1, just like strings.


4. Using the ‘+=’ operator:

The ‘+=’ operator can also be used to add multiple elements to the end of a list. For example:

08

Accessing List Elements

Now that we know how to create and add elements to a list, it’s time to unleash the power of list manipulation by exploring how to access individual elements. Accessing elements within a list is an essential skill that every Python programmer needs to master. It allows us to retrieve specific pieces of information from the list, such as the highest value or the name of the first element. So, let’s dive in and explore how to access the elements within a list.


1. Indexing:

Indexing is the process of retrieving a specific element from a list based on its position or index. In Python, list indexing starts at 0, meaning that the first element in a list has an index of 0, the second element has an index of 1, and so on.

001

To access an element in a list, we can use its index value inside square brackets “[]” after the name of the list. For example, if we have a list named “my_list” and we want to access its first element. We can do so as shown below:

 

new_element = mylist[0]

10
2. Negative Indexing:

 

Negative indexing is a way of accessing elements in a list by counting backwards from the end of the list. 

 

In negative indexing, the last element in a list has an index value of -1. The second to last element has an index value of -2, and so on.

11

Negative indexing provides a convenient way to access elements from the end of the list without the need to know the exact length of the list. It can be particularly useful in situations where the length of the list is not known in advance. It can also be used when working with large lists were counting from the end can be faster than counting from the beginning.

Note: Keep in mind that if we try to access an index that does not exist in the list, we will get an IndexError. Therefore, it is always important to make sure that the index value we are using is within the range of the list.

3. Slicing a List

 

Slicing is another useful technique for accessing elements within a list. Slicing allows us to extract a subset of elements from a list based on their position within the list. In other words, we can slice a list to create a new list that contains only a specific range of elements.

 

The basic syntax for slicing a list in Python is as follows:

 

Syntax: new_list = list[start:stop:step]

  • Start: is the starting index for the slice.
  • Stop: stopping index for the slice (exclusive)
  • Step: the step size between the elements in the slice.

It is important to note that slicing does not modify the original list, but instead returns a new list containing the sliced elements.

 

Now let us look at an example of how slicing actually works.

12

Here my_list and my_list2 are sub list of my_list containing the elements from index 2 to index 6 and index 0 to 9 with step-size of 2.

 

4. Accessing Nested Lists

A nested list is a list that has other lists as its elements. This means that each item in the list is actually a list itself. Nested lists allow us to create a structure where each level of the list contains its own set of sub-lists, creating a hierarchy of lists within lists.

For example, consider the following nested list:

 

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

This list contains three sub-lists, each of which contains three elements. 

 

We can access the elements of the sub-lists using indexing and slicing, just like we did with a regular list. 

 

To access an element in a sub-list, we first specify the index of the sub-list, and then the index of the element within that sub-list. 

 
Example:

For example, to access the element at row 2, column 3 (i.e., the number 6) in the above nested list, we would use the following code:

 

my_list[1][2]

Here, my_list[1] refers to the second sub-list (remember, indexing starts from 0), and my_list[1][2] refers to the third element within that sub-list.

13

To access the element ‘5’ in this list, we would use indexing twice, like this:

14

We can also use slicing to access a sub list within a sub list. For example, to access the sub list [4, 5], we can use slicing like this:

 

[4,5] is present in the index position [1] of the main list, in the sub-list present at the main list at [1] elements [4,5] start from index position 0 to 1 i.e., in terms of slicing we can say [0:1]

my_list[1][0:2]

15
Take Away:

And thus, in conclusion we can say that Accessing elements in a nested list can be done by chaining multiple index operators together. By using the index operator on the outer list to access the inner list and then using the index operator on the inner list to access the desired element, we can navigate through the levels of the nested list to retrieve the desired element.

List Operations in Python

List operations in Python refer to various methods and functions that can be used to manipulate and perform operations on lists. These operations include adding or removing elements, membership testing, identity testing, copying, and more. By using these operations, we can modify the contents of a list to suit our needs and perform various tasks efficiently.

Let us take a look at some of the most commonly used list operations.

 

1. List Concatenation

List concatenation is the process of combining two or more lists into a single list. In Python, this can be done using the ‘+’ operator or the ‘extend()’ method. Concatenating lists can be useful when we need to combine the data from multiple lists. It can also be used when we need to create a new list that includes elements from multiple existing lists.

16
2. List Repetition

List repetition is the process of creating a new list by repeating the elements of an existing list a certain number of times. In Python, we can use the multiplication operator to repeat a list a certain number of times. This can be useful when we want to create a new list with a specific number of repeated elements.

17

In this example, we first create a list called my_list with three elements. We then use the * operator to repeat the list three times, resulting in a new list called new_list with nine elements. We then print the new list, which contains the elements of the original list repeated three times.


3. Membership Testing

Membership testing as we have discussed in strings is a process of checking if an element or a value is present in a list or not. In Python, we can use the ‘in’ and ‘not’ in operators to perform membership testing on a list. These operators return a Boolean value True if the element is present in the list and False otherwise.

 

Here’s an example of membership testing in Python:

18

In this example, we have a list of fruits and we are testing for membership using the ‘in’ and ‘not in’ operators. The first print statement checks if ‘apple’ is in the list and returns True. The second print statement checks if ‘pear‘ is in the list and returns False. The third print statement checks if ‘banana’ is not in the list and returns False. The fourth print statement checks if ‘kiwi’ is not in the list and returns True.


4. Identity Testing

Identity testing is a concept in Python where the is and is not operators are used to check if two objects or variables refer to the same object in memory. It checks whether two objects have the same identity or not, i.e., if they are the same object in memory.

 

For example, let’s consider two variables a and b containing the same list [1, 2, 3]

 

If we use the identity operator ‘is’ to check if a and b refer to the same object, it will return False, as they are two separate objects with the same value. 

 

However, if we assign a to c (c = a) where c is another variable, and then check if c and a are the same object using the ‘is’ operator, it will return True, as c is simply a reference to the same object in memory as a.

19

Those where some of the major operations falling under the topic lists in python, now let us take a look at some of the most prominently used list methods in python.

List Methods in Python.

List methods are built-in functions in Python that allow us to manipulate and modify lists. These methods can be used to add, remove, and modify elements in a list, as well as perform other useful operations like sorting, reversing, and copying lists. By using these methods, we can make our code more efficient and concise. Let us take a look at some of the major list methods in python.

 

  1. append()
  2. extend()
  3. insert()
4. Python Method: remove()


The remove() method is a built-in function in Python that is used to remove the first occurrence of a specified element from a list. If the specified element is not found in the list, it raises a ValueError

 

This method modifies the original list in place, and does not return any value.

 

Syntax: list.remove(element)

  • List: is the list in which the operation is to be performed
  • Element: value that we want to remove from the list.


Here’s an example of how to use the ‘remove()’ method to remove an element from a list:

20

In this example, the remove() method is used to remove the ‘banana’ element from the fruits list. After the removal, the updated list is printed using the print() function.


5. Python Method: pop()

The pop() method is a built-in function in Python that removes and returns the element at the given index (defaulting to the last element) in a list. It modifies the original list.

 

Syntax: list.pop([index])

 

  • List: is the list in which the operation is to be performed
  • Index: the index value from which the element needs to be removed

 

If index is not provided, pop() removes and returns the last element of the list.

Example:

21

Here first time we used pop() we did not give any index value, so it by default popped of ‘cherry’ which is the last element on the list.

 

Then we used pop() again with an index value of 1 to remove ‘banana’ which is present at the first index of the fruits.


5. Python Method: clear()

The clear() method is a built-in Python function used to remove all the elements from a list. It does not return any value, but it modifies the original list. After the clear() method is called, the list will be empty.

 

Syntax: list.clear()

Example:

22
7. Python Method: copy()

 

The copy() method is used to create a copy of a list. It returns a new list that contains all the elements of the original list. 

 

The new list is a separate object from the original list, so any changes made to the new list will not affect the original list, and vice versa.

 

The copy() method can be used in two ways:

  • Shallow copy: It creates a new list, but the elements of the new list are references to the same objects as the original list. If the objects in the original list are mutable, changes made to those objects will be reflected in both the original and the copied list.

Syntax: new_list = old_list.copy()

23
  • Deep copy: It creates a copy creates a new list and new objects for each of the elements in the original list. This means that changes made to the objects in the original list will not be reflected in the copied list.

Syntax: 

import copy

new_list = copy.deepcopy(old_list)

  • old_list: the original list that you want to copy.
  • new_list: new deep copy of the original list.
  • deepcopy(): method that creates a new copy of the original list.

Here is an example that provides a detailed explanation about the various copy methods in python.

24
8. Python Method: count()

The count() method is a built-in function in Python that returns the number of times a specified element appears in a list. It takes a single argument, which is the value to be counted, and returns an integer representing the count of that value in the list. If the value is not found in the list, the method returns 0.

 

Syntax: list.count(element)

 

Here, list is the list on which the count() method is being called, and element is the element whose occurrence in the list needs to be counted. The method will give the number of times the element had appeared in the list.

Example:

25

In this example, we have a list of fruits that includes three bananas. We use the count() method to count the number of times the string ‘banana’ appears in the list. 

 

Python Method: index()

The index() method is used to find the first occurrence of a specified element in a list and return its index. If the element that we have searched for is not found within the scope of the list, the method will throw a ValueError.

 

Syntax: list_name.index(element, start, end)

  • list_name: name of the list you want to search for the element in.
  • elementelement you want to find the index of.
  • start (optional): starting index for the search. If not specified, the search starts from the beginning of the list.
  • end (optional): ending index for the search. If not specified, the search continues to the end of the list.
26

In this example, index() is used to find the index of the first occurrence of the string ‘banana’ in the list my_list. The method returns 1, which is the index of the first ‘banana’ element in the list.

 

Python Method: sort()

The sort() method in Python is a built-in method that allows you to sort elements in a list in ascending or descending order. It modifies the original list in place and returns None. The syntax for sort() is as follows:

 

Syntax: list_name.sort(reverse=False)

 

The optional reverse parameter can be set to True to sort the list in descending order. By default, reverse is set to False, which means that the list is sorted in ascending order. sort() method only works on lists that contain elements of the same data type, such as integers.

 

Here’s an example of using the sort() method to sort a list of numbers in ascending order:

27

This will modify the original numbers list and sort it in ascending order. If you want to sort it in descending order, you can pass the reverse=True argument to the sort() method like this:

28
Python Method: reverse()

The reverse() method in Python is used to reverse the order of elements in a list. It modifies the original list in place and returns None. The syntax for reverse() is as follows:

 

Syntax: list.reverse()

where list is the name of the list on which the reverse() method is called.

 

Here’s an example:

29

Conclusion:

Lists are an essential data structure in Python that allows us to store and manipulate a collection of data. They are ordered, mutable, and allow duplicate elements. Lists can contain any data type, including other lists, making them a versatile tool in programming.

 

Lists are useful whenever we need to store and manipulate a collection of data in a specific order. They can be used for a wide range of tasks, such as data analysis, mathematical operations, and text processing. This data type is also an excellent choice for tasks that require dynamic allocation of memory, such as building a program that stores user input.

 

In this blog we have covered all you guys need to know about lists in our next blog we will be diving into the data type of tuples so stay tuned and follow 1stepgrow.

Christmas & New Year Offer

30% Off

On All Our Courses:)

Enroll Now and Get Future Ready!!