Python List Tutorial with Examples

Python Lists

In Python, a list is an intrinsic data structure that enables the storage of numerous items within a single variable. Lists rank among the most frequently utilized data structures in Python due to their mutable nature, ordered arrangement, and capability to accommodate various types of elements. They offer a versatile approach to managing data collections and are equipped with a plethora of beneficial built-in methods.

Let us take a look at a simple example of a list.

Example

Example

# creating a list

L = [20, 'Example', 35.75, [20, 40, 60]]

print(L)

Output:

Output

[20, 'Example', 35.75, [20, 40, 60]]

Explanation:

In the above example, we have created a simple list consisting of four elements of different data types. Each element in this list is indexed, meaning it can be accessed using its position in the list, as shown below:

  • L[0] = 20 (Integer)
  • L[1] = 'Example' (String)
  • L[2] = 35.75 (Float)
  • L[3] = [20, 40, 60] (Nested List)
  • Characteristics of Python Lists

A list in Python is a type of data structure characterized by the following features:

  • Ordered: The elements within a list retain the sequence of their insertion. When an element is added at a particular index, it will stay in that position until it is intentionally altered.
  • Changeable (Mutable): Python lists permit alterations to their elements even after they have been created.

Let us examine the subsequent illustration that demonstrates the mutability of Lists.

Example

Example

# creating a list

my_lst = [25, 16.25, 'Example', [20, 40, 60], 3e8]

# changing the element of the list

my_lst[1] = 'welcome'

print(my_lst)

Output:

Output

[25, 'welcome', 'Example', [20, 40, 60], 300000000.0]

In this illustration, we have created a list and employed indexing to modify one of its elements.

  • Heterogeneous (Varied Data Types): A single list is capable of containing various data types, such as integers, strings, floats, and even another list.

Let us examine the subsequent example that illustrates how a List functions as a heterogeneous data structure.

Example

Example

# creating a list

mixed_lst = [10, 'Hello', 5.23, [7, 12]]

print(mixed_lst)

Output:

Output

[10, 'Hello', 5.23, [7, 12]]

In this instance, we have created a list that includes various data types, including integers, strings, floats, and even another list.

  • Permits Duplicates: A list is a type of data structure that can accommodate duplicate entries.

Consider an example that demonstrates how the List collection permits duplicate entries.

Example

Example

# creating a list

dup_lst = [12, 51, 12, 5, 3, 5, 77, 42, 2, 12, 12, 6, 6]

print(dup_lst)

Output:

Output

[12, 51, 12, 5, 3, 5, 77, 42, 2, 12, 12, 6, 6]

In this instance, we have created a list that contains repeated values.

Operations on List in Python

There are many operations that we can perform on Python list. Some of them are listed below:

  • Creating a List
  • Accessing List Elements
  • Adding Elements to List
  • Updating Elements into List
  • Removing Elements from the List
  • Iterating Over Lists

Now, we will explore how to implement these list operations through various examples.

Creating a List

In Python, lists can be formed by placing elements inside square brackets , with each element separated by commas.

Let's examine an example that illustrates the process of constructing a list.

Example

Example

# Creating lists

empty_list = []

numbers = [11, 4, 23, 71, 58]

mixed_list = [1, "Hello", 6.74, True]

print(empty_list)

print(numbers)

print(mixed_list)

Output:

Output

[]

[11, 4, 23, 71, 58]

[1, 'Hello', 6.74, True]

Explanation:

In the preceding example, we have generated three distinct kinds of lists: an empty list, a list that contains solely integer values, and a list made up of elements with varying data types. We subsequently displayed these lists for reference purposes.

Accessing List Elements

Elements within a list can be retrieved through indexing. Python employs zero-based indexing, which indicates that the initial element is assigned an index of 0. To access the element located at a specific position, we can utilize the index number enclosed within square brackets ''.

Below is an illustration demonstrating how to retrieve an element from a specified list.

Example

Example

# Creating lists

my_list = [15, 23, 47, 32, 94]

print(my_list[0])

print(my_list[-1])

Output:

Output

15

94

Explanation:

In the preceding example, we have generated three distinct categories of lists: an empty list, a list populated solely with integer values, and a list that contains elements of various data types. Subsequently, we printed these lists for reference purposes.

Adding Elements to the List

Python offers accessibility to add elements to a list. This can be achieved using the various options available for us:

  • append : Adds a single element to the end of the list.
  • insert : Inserts an element at a specific index.
  • extend: Adds multiple elements to the end of the list.

Below is an illustration demonstrating various techniques for inserting elements into a list.

Example

Example

# creating a list

my_lst = [7, 3, 4]

# Method 1: using append()

my_lst.append(6)

print(my_lst)

# Method 2: using insert()

my_lst.insert(1, 13)

print(my_lst)

# Method 3: using extend()

my_lst.extend([14, 43, 37])

print(my_lst)

Output:

Output

[7, 3, 4, 6]

[7, 13, 3, 4, 6]

[7, 13, 3, 4, 6, 14, 43, 37]

Explanation:

In the example provided, a list has been established, and three distinct methods have been utilized – append, insert, and extend – to add items to the list. Consequently, the append method has placed an item at the conclusion of the list. The insert method has positioned an item in the second spot within the list. Meanwhile, the extend method has incorporated several elements simultaneously at the end of the list.

Updating Elements into a List

Elements within a list can be modified through the use of indexing. Below is an illustration demonstrating the method of updating elements in a list.

Example

Example

# creating a list

my_lst = [17, 23, 35]

# Updating the second element

my_lst[1] = 52

print(my_lst)

Output:

Output

[17, 52, 35]

Explanation:

In the example provided, a list has been established. Subsequently, we utilized indexing to modify the second element within that list.

Removing Elements from the List

Python provides several methods to remove elements from a list:

  • remove(value): Removes the first occurrence of the value.
  • pop(index) : Removes the element at a specific index (or the last element by default).
  • del statement : Deletes an element or the entire list.

Let’s examine the subsequent example that illustrates multiple methods for eliminating an item from a list.

Example

Example

# creating a list

my_lst = [14, 25, 43, 2, 33]

# Method 1: using remove()

my_lst.remove(43)

print(my_lst)

# Method 2: using pop()

my_lst.pop(-1)

print(my_lst)

# Method 3: using del keyword

del my_lst[0]

print(my_lst)

Output:

Output

[14, 25, 2, 33]

[14, 25, 2]

[25, 2]

Explanation:

In the previously mentioned example, we established a list and employed three distinct techniques – remove, pop, and the del keyword – to eliminate items from the list. Consequently, the remove method successfully deleted the designated item from the list. Meanwhile, the pop method extracted the element located at the given index from the list. Lastly, the del keyword was utilized to remove the element from the list at the indicated index.

Iterating Over Lists

In Python, we can traverse lists through the use of loops. For example, let’s illustrate how to utilize both the 'for' loop and the 'while' loop to go through the items in a specified list.

Example

Example

# creating a list

my_lst = [12, 23, 9, 17, 41]

print("Iterating List using 'for' loop:")

# Using for loop

for ele in my_lst:

    print(ele)

print("\nIterating List using 'while' loop:")

# Using while loop

i = 0

while i < len(my_lst):

    print(my_lst[i])

    i += 1

Output:

Output

Iterating List using 'for' loop:

12

23

9

17

41

Iterating List using 'while' loop:

12

23

9

17

41

Explanation:

In this illustration, we have constructed a list. Subsequently, we employed a for loop to traverse through the elements of the list. Following that, we utilized a while loop, initializing the index variable, i, to 0; and incremented it while displaying the element located at the current index from the list.

Nested Lists in Python

A Nested List in Python refers to a list that contains several sub-lists, which are divided by commas. Each sub-list can hold elements of varying data types. Furthermore, the inner lists (also known as sub-lists) have the capability to include additional lists, resulting in multiple layers of nesting.

In Python, nested lists can be utilized to construct hierarchical data arrangements, matrices, or more straightforwardly, a collection of lists within a list. Python offers a variety of tools that facilitate the efficient and effective management of nested lists, enabling users to execute standard operations on these structures.

Let’s examine an example that demonstrates various operations on a nested list in Python.

Example

Example

# creating a nested list

nested_lst = [[14, 6, 8], [13, 18, 25], [72, 48, 69]]

print("Nested List:", nested_lst)

print("\nAccessing Elements of Nested List:")

# Accessing elements

print("nested_lst[0]:", nested_lst[0])

print("nested_lst[0][1]:", nested_lst[0][1])

print("\nIterating through Nested list using 'for' loop:")

# Iterating through a nested list

for sublist in nested_lst:

  for item in sublist:

    print(item)

print("\nAdding element to Nested list:")

# Adding elements

nested_lst[0].append(10)

print("New Nested List:", nested_lst)

Output:

Output

Nested List: [[14, 6, 8], [13, 18, 25], [72, 48, 69]]

Accessing Elements of Nested List:

nested_lst[0]: [14, 6, 8]

nested_lst[0][1]: 6

Iterating through Nested list using 'for' loop:

14

6

8

13

18

25

72

48

69

Adding element to Nested list:

New Nested List: [[14, 6, 8, 10], [13, 18, 25], [72, 48, 69]]

Explanation:

In the preceding example, a nested list has been established. Subsequently, we employed indexing to retrieve specific elements from this list. Initially, we accessed the outer list's element by utilizing nestedlst[0], which yields the inner list as the output, specifically [14, 6, 8]. In the following instance, we retrieved an element from the inner list through nestedlst0, which provides the value of that inner list element, namely 6. Next, we executed an iteration over the nested list via a nested for loop. Finally, we included an element to the nested list by utilizing the append method.

Finding the Length of a List

Python includes a built-in function known as len that allows you to ascertain the total count of items within a list.

Syntax:

Example

len(list_name)

Consider an example that demonstrates the application of the len function with lists.

Example

Example

# creating a list

lst_one = [15, 61, 23, 6, 87, 5, 93]

# using the len() function to find the size of the list

no_of_ele = len(lst_one)

print("Given List:", lst_one)

print("Number of Elements in the given list:", no_of_ele)

Output:

Output

Given List: [15, 61, 23, 6, 87, 5, 93]

Number of Elements in the given list: 7

Explanation:

In the preceding example, a collection of integers was established. Subsequently, the len function was utilized to determine the length of the list, which was then assigned to a variable. Finally, both the list and the value of the variable were displayed as output.

Sorting a List

Python includes a function known as sort that enables users to arrange the items of a list directly. Below, we will examine an example that demonstrates how the sort function operates.

Example

Example

# creating a list

lst_one = [15, 61, 23, 6, 87, 5, 93]

print("Given List:", lst_one)

# sorting the list in ascending order (by default)

lst_one.sort()

print("Sorted List:", lst_one)

Output:

Output

Given List: [15, 61, 23, 6, 87, 5, 93]

Sorted List: [5, 6, 15, 23, 61, 87, 93]

Explanation:

In the example provided above, a list has been generated, and the sort method has been applied to arrange its elements in ascending order.

Python Sorted List Example

Python provides a function named sorted that operates in a manner akin to the sort method; nevertheless, it generates a new list as its output.

Let us examine the subsequent example that demonstrates the application of the sorted function.

Example

Example

# creating a list

lst_one = [15, 61, 23, 6, 87, 5, 93]

# sorting the list

new_lst = sorted(lst_one)

print("Given List:", lst_one)

print("Sorted List:", new_lst)

Output:

Output

Given List: [15, 61, 23, 6, 87, 5, 93]

Sorted List: [5, 6, 15, 23, 61, 87, 93]

Explanation:

In this illustration, we have generated a list and employed the sorted function to arrange the elements of the list in order.

Reversing a List

The Python List includes a method known as reverse which enables users to invert the sequence of the items within the list.

Let's examine the subsequent example that demonstrates the application of the reverse method.

Example

Example

# creating a list

lst_one = [15, 61, 23, 6, 87, 5, 93]

print("Given List:", lst_one)

# reversing the list

lst_one.reverse()

print("Reversed List:", lst_one)

Output:

Output

Given List: [15, 61, 23, 6, 87, 5, 93]

Reversed List: [93, 5, 87, 6, 23, 61, 15]

Explanation:

In the preceding example, we generated a list and utilized the reverse method to invert the sequence of the elements contained within that particular list.

Finding the Largest and Smallest Number in a List

To determine both the maximum and minimum values within a list, we can utilize the functions max and min as demonstrated in the example below:

Example

Example

# creating a list

lst_one = [15, 61, 23, 6, 87, 5, 93]

print("Given List:", lst_one)

# finding largest and smallest number

print("Largest Number:", max(lst_one))

print("Smallest Number:", min(lst_one))

Output:

Output

Given List: [15, 61, 23, 6, 87, 5, 93]

Largest Number: 93

Smallest Number: 5

Explanation:

In the preceding illustration, a list was generated. Subsequently, the max function was employed to identify the highest value within the specified list. Additionally, the min function was utilized to ascertain the lowest value.

Calculating Sum of Elements in a List

To compute the total of elements within a list, one can utilize Python's built-in sum function, as demonstrated in the example below:

Example

Example

# creating a list

lst_one = [15, 61, 23, 6, 87, 5, 93]

print("Given List:", lst_one)

# finding sum of the elements in the list

print("Sum of the Elements in the list:", sum(lst_one))

Output:

Output

Given List: [15, 61, 23, 6, 87, 5, 93]

Sum of the Elements in the list: 290

Explanation:

In the preceding illustration, we have constructed a list. Subsequently, we utilized the sum function to determine the total of the elements contained within the specified list.

Conclusion

Python lists offer a flexible method for managing a collection of data elements. They come equipped with features such as appending, inserting, modifying, and iterating, which make them fundamental to numerous Python applications. Gaining proficiency in lists is crucial for effective programming in Python.

Python List – FAQs

1. What will be the output of the following code?

Example

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

print(lst_one[2])

2. What method is used to add an element at the end of a list?

  • insert
  • extend
  • append
  • add

3. What will be the output of the following code?

Example

num_lst = [13, 22, 15]

num_lst.append([44, 25])

print(num_lst)
  • [13, 22, 15, 44, 25]
  • [13, 22, 15, [44, 25]]
  • [13, 22, 15, (44, 25)]
  • Error

4. What will be the output of the following code?

Example

num_lst = [13, 22, 15, 17, 4, 6]

print(len(num_lst))
  • Error

5. What is the output of the following code?

Example

lst_one = [12, 21, 43]

lst_two = [15, 35]

print(lst_one + lst_two)
  • [12, 21, 43, 15, 35]
  • [12, 21, 43, [15, 35]]
  • [[12, 21, 43], [15, 35]]
  • Error

Input Required

This code uses input(). Please provide values below: