What are Lists in Python?

Imagine having a magical container that can hold a multitude of items in a specific order. That’s precisely what Python lists are! In simple terms, a list is an ordered collection of elements, allowing you to store different types of data, such as numbers, names, or even other lists, all in one place. This incredible flexibility makes lists an essential tool in your Python toolkit.

So, get ready yourself to unlock the full potential of this versatile data type that will empower you to organize and manipulate your data like a pro. In this tutorial, we will take you on a step-by-step journey, providing clear instructions and practical examples to help you master the art of Python lists. Whether you’re a beginner or already have some experience, we’ve got you covered. So, grab your coding hat and let’s embark on this exciting adventure together!

Python List syntax

Python lists are denoted by enclosing the elements within square brackets [ ]. Elements within the list are separated by commas. Let’s dive into an example to illustrate this:

favorite_destinations = ['Bali', 'Paris', 'Hawaii', 'Maldives']

In this example, we have created a list called favorite_destinations that contains popular travel spots. Each destination is represented as a string, enclosed in quotes, and separated by commas. Now, let’s unravel the secrets of manipulating these captivating lists!

What is list() function in Python?

Creating lists is an exciting endeavor, and Python offers a handy function called list() to help us on our journey. This function allows you to convert an iterable object, such as a string or a tuple, into a list. Let’s explore an example using a list of popular celebrities:

celebrities = list(('Brad Pitt', 'Angelina Jolie', 'Leonardo DiCaprio', 'Jennifer Aniston'))

In this example, we utilize the list() function to convert a tuple of celebrity names into a list. Now, we’re armed with a powerful tool to create captivating lists in Python!

How to create Python list?

Creating a list from scratch is a breeze in Python. Simply enclose the elements within square brackets [ ], separated by commas. Let’s create a list of favorite fruits to illustrate this:

favorite_fruits = ['apple', 'banana', 'orange', 'strawberry']

In this example, we have crafted a delightful list of our favorite fruits. Each fruit name is a string, enclosed in quotes, and separated by commas. The possibilities for list creation are endless!

I. Accessing List Elements

Once you’ve created a list, you’ll want to access and retrieve specific elements. Python provides a simple indexing mechanism to access individual elements within a list. Let’s say we want to retrieve the second element from our favorite_fruits list:

Example Code
favorite_fruits = ['apple', 'banana', 'orange', 'strawberry'] second_fruit = favorite_fruits[1] print("One of my favorite fruits is " + second_fruit)

In this example, we access the second element of the list using the index 1 (remember, Python uses zero-based indexing). We then print a friendly message incorporating the retrieved fruit. The world of list access is at our fingertips!

Output
One of my favorite fruits is banana

II. Modifying List Elements

Lists are not static entities; they are dynamic and mutable. This means we can modify the elements within a list to reflect changes in our data. Let’s see how we can update the favorite_fruits list:

Example Code
favorite_fruits = ['apple', 'banana', 'orange', 'strawberry'] favorite_fruits[0] = 'pineapple' print("After trying new fruits, my favorite list now includes: " + ', '.join(favorite_fruits))

In this example, we update the first element of the list to reflect a change in our taste. We then print a message displaying the modified list. Lists grant us the power to adapt and evolve!

Output
After trying new fruits, my favorite list now includes: pineapple, banana, orange, strawberry

Python provides several useful methods to modify list elements based on specific requirements. Let’s explore a couple of them:

III. Adding Elements to the End – using append()

The append() method allows you to add new elements to the end of a list. Let’s consider an example where we have a list of fruits:

Example Code
fruits = ['apple', 'banana', 'orange'] fruits.append('grape') print("After adding a fruit, the updated list of fruits is:", fruits)

In this example, we use fruits.append('grape') to add the fruit ‘grape’ to the end of the fruits list. The append() method modifies the original list by adding the specified element to the end.

Output
After adding a fruit, the updated list of fruits is: [‘apple’, ‘banana’, ‘orange’, ‘grape’]

IV. Inserting Elements at a Specific Position

The insert() method allows you to insert a new element at a specific position in a list. Let’s see an example where we have a list of numbers:

Example Code
numbers = [1, 2, 3, 4, 5] numbers.insert(2, 10) print("After inserting a number, the updated list of numbers is:", numbers)

In this example, we use numbers.insert(2, 10) to insert the number 10 at index 2 of the numbers list. The insert() method shifts the existing elements to the right and adds the new element at the specified position.

Sorting Python List Elements

Python Sorting allows us to organize our data in a particular order, making it easier to analyze, search, and manipulate. Python provides several methods to sort lists, each offering different functionalities. So, let’s explore the art of sorting in Python!

I. Sorting a List in Ascending Order

To sort a list in ascending order, we can use the sort() method. Let’s consider an example where we have a list of numbers:

Example Code
numbers = [5, 2, 8, 1, 3] numbers.sort() print("The sorted list in ascending order is:", numbers)

For this example, we use the sort() method to sort the numbers list in ascending order. The sort() method modifies the original list, rearranging the elements in ascending order. After sorting, we print the updated list to display the sorted result.

Output
The sorted list in ascending order is: [1, 2, 3, 5, 8]

II. Sorting a List in Descending Order

If we want to sort a list in descending order, we can utilize the sort() method with the reverse parameter. Let’s modify our previous example to sort the list in descending order:

Example Code
numbers = [5, 2, 8, 1, 3] numbers.sort(reverse=True) print("The sorted list in descending order is:", numbers)

In this modified example, we pass the reverse=True argument to the sort() method. This instructs Python to sort the numbers list in descending order. The sort() method, combined with the reverse parameter, enables us to achieve the desired sorting order.

Output
The sorted list in descending order is: [8, 5, 3, 2, 1]

III. Sorting a List Without Modifying the Original List

Sometimes, we may want to sort a list without modifying the original list. In such cases, we can use the sorted() function. Let’s consider an example where we have a list of names:

Example Code
names = ['Alice', 'Bob', 'Charlie', 'David'] sorted_names = sorted(names) print("The sorted list without modifying the original list is:", sorted_names)

In this example, we use the sorted() function to sort the names list without modifying the original list. The sorted() function returns a new sorted list, leaving the original list intact. We assign the sorted list to the sorted_names variable and print the result.

Output
The sorted list without modifying the original list is: [‘Alice’, ‘Bob’, ‘Charlie’, ‘David’]

IV. Custom Sorting with the key Parameter

Python allows us to perform custom sorting by providing a key function that determines the sorting criteria. Let’s consider an example where we have a list of names, and we want to sort them based on their lengths:

Example Code
names = ['Alice', 'Bob', 'Charlie', 'David'] sorted_names = sorted(names, key=len) print("The sorted list based on name lengths is:", sorted_names)

In this example, we pass the key=len argument to the sorted() function. This instructs Python to sort the names list based on the length of each name. The len function serves as the key function, determining the sorting criteria. The result is a sorted list based on name lengths.

Output
The sorted list based on name lengths is: [‘Bob’, ‘Alice’, ‘David’, ‘Charlie’]

Till here, You have explored various ways to create, access, modify and sort list elements. Now, let’s explore how to remove items from a list.

Removing Python List Elements

Sometimes, you may need to clean up your list by removing unwanted elements or specific values. Python provides several methods to accomplish this task. So, let’s learn how to tidy up our lists by removing items!

I. Removing List Items by Index

One straightforward method to remove an item from a list is by using the del statement followed by the index of the item you want to remove. Let’s consider an example where we have a list of favorite books:

Example Code
favorite_books = ['Harry Potter', 'To Kill a Mockingbird', 'Pride and Prejudice', 'The Great Gatsby'] del favorite_books[2] print("After removing a book, my updated favorite books list is: " + ', '.join(favorite_books))

In this example, we use del favorite_books[2] to remove the book at index 2 from the favorite_books list. The del statement modifies the original list by deleting the specified item. After removing the book, we print the updated list to confirm the change.

Output
After removing a book, my updated favorite books list is: Harry Potter, To Kill a Mockingbird, The Great Gatsby

II. Removing List Items by Value

Sometimes, you may want to remove an item from a list based on its value rather than its index. Python provides the remove() method to accomplish this task. Let’s take a look at an example where we have a list of favorite movies:

Example Code
favorite_movies = ['The Shawshank Redemption', 'Inception', 'The Dark Knight', 'The Matrix'] favorite_movies.remove('Inception') print("After removing a movie, my updated favorite movies list is: " + ', '.join(favorite_movies))

In this example, we use favorite_movies.remove('Inception') to remove the movie ‘Inception’ from the favorite_movies list. The remove() method searches for the specified value in the list and removes the first occurrence of it. Again, we print the updated list to verify the change.

Output
After removing a movie, my updated favorite movies list is: The Shawshank Redemption, The Dark Knight, The Matrix

III. Clearing the Entire List

If you want to remove all items from a list and start fresh, Python provides the clear() method. Let’s see an example:

Example Code
shopping_list = ['apples', 'bananas', 'milk', 'bread'] shopping_list.clear() print("After clearing the list, my shopping list is now empty:", shopping_list)

In this example, we use shopping_list.clear() to remove all items from the shopping_list. The clear() method empties the list, leaving it with no elements. We then print the list to confirm that it is now empty.

Output
After clearing the list, my shopping list is now empty: []

Now that you have learned how to create, modify and remove Python lists, let’s dive into the exciting realm of list indexing.

Python List Indexing

When working with Python lists, one of the key skills to master is list indexing. Indexing allows you to access individual elements within a list by referring to their position or index. Python uses zero-based indexing, which means the first element in a list is located at index 0, the second element at index 1, and so on. Let’s delve into the world of list indexing and discover how it can help us unveil the treasures hidden within our lists.

I. Accessing List Elements with Indexing

To access a specific element in a list, you can use square brackets [] and provide the index of the desired element. Let’s consider an example where we have a list of favorite colors:

favorite_colors = ['blue', 'red', 'green', 'yellow']

To access the first element, which is blue, we use the index 0:

Example Code
favorite_colors = ['blue', 'red', 'green', 'yellow'] first_color = favorite_colors[0] print("My favorite color is " + first_color)

In this example, we use favorite_colors[0] to access the first element of the list. By incorporating this indexing technique, we can retrieve specific elements and perform further operations on them.

Output
My favorite color is blue

II. Modifying List Elements with Indexing

Not only can you access list elements using indexing, but you can also modify them to reflect changes in your data. Python lists are mutable, meaning you can update individual elements. Let’s consider the previous example and change the second element from red to purple:

Example Code
favorite_colors = ['blue', 'red', 'green', 'yellow'] favorite_colors[1] = 'purple' print("After experimenting, my updated favorite colors are: " + ', '.join(favorite_colors))

In this example, we assign the value 'purple' to favorite_colors[1], which corresponds to the second element of the list. By doing so, we effectively modify the list to include our new favorite color. This flexibility allows you to adapt your lists as your preferences or data evolve.

Output
After experimenting, my updated favorite colors are: blue, purple, green, yellow

III. Python List Negative Indexing

In addition to positive indexing, which starts from the beginning of the list, Python also supports negative indexing. Negative indices allow you to access elements starting from the end of the list. The last element has an index of -1, the second-to-last element has an index of -2, and so on. Let’s explore an example:

Example Code
favorite_fruits = ['apple', 'banana', 'orange', 'strawberry'] last_fruit = favorite_fruits[-1] print("The last fruit in my list is " + last_fruit)

In this example, we use the negative index -1 to access the last element of the list, which is strawberry. Negative indexing is a handy tool when you want to access elements from the end of the list without knowing its length.

Output
The last fruit in my list is strawberry

Python List Slicing

Building upon our understanding of list indexing, let’s now venture into the realm of list slicing. List slicing allows you to extract a portion or subset of a list by specifying a range of indices. This powerful technique enables you to work with a specific section of a list without modifying the original list. So, let’s dive into the world of list slicing!

I. Slice A Python List

Python List slicing utilizes a similar syntax to list indexing but introduces a range of indices within the square brackets []. The range is defined by providing the starting index and the ending index, separated by a colon :. The starting index is inclusive, while the ending index is exclusive. Let’s delve into an example to illustrate list slicing in action:

Example Code
favorite_colors = ['blue', 'red', 'green', 'yellow', 'purple'] subset_colors = favorite_colors[1:4] print("A subset of my favorite colors is: " + ', '.join(subset_colors))

In this example, we slice the favorite_colors list from index 1 to index 4. The resulting subset includes the elements at indices 1, 2, and 3. Notice how the element at index 4 is not included. This is a fundamental aspect of list slicing in Python.

Output
A subset of my favorite colors is: red, green, yellow

II. Specifying Slicing Range

Python List slicing offers flexibility in specifying the range of indices. You can choose to omit the starting or ending index to slice from the beginning or until the end of the list, respectively. Let’s explore some examples:

Example Code
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] subset_1 = numbers[:5] # Slicing from the beginning until index 5 subset_2 = numbers[5:] # Slicing from index 5 until the end subset_3 = numbers[2:8:2] # Slicing from index 2 to index 8 with a step size of 2 print("Subset 1:", subset_1) print("Subset 2:", subset_2) print("Subset 3:", subset_3)

In subset_1, we omit the starting index, which implies slicing from the beginning of the list until index 5. In subset_2, we omit the ending index, resulting in slicing from index 5 until the end of the list. In subset_3, we introduce a step size of 2, which selects every second element within the specified range.

Output
Subset 1: [1, 2, 3, 4, 5]
Subset 2: [6, 7, 8, 9, 10]
Subset 3: [3, 5, 7]

III. Python List Negative Slicing

Similar to Python list negative indexing, negative slicing allows you to slice a list from the end, providing a convenient way to extract elements without knowing the length of the list. Let’s take a look at an example:

Example Code
fruits = ['apple', 'banana', 'orange', 'strawberry', 'mango'] subset_fruits = fruits[-3:-1] print("A subset of fruits from the list is:", subset_fruits)

In this example, we use negative indices to slice a subset of the fruits list. The range -3 to -1 selects the elements from the third-to-last position until the second-to-last position.
Output
A subset of fruits from the list is: [‘orange’, ‘strawberry’]

List Concatenation: Bringing Lists Together

Let’s explore the concept of list concatenation, which allows us to bring multiple lists together into a single list. List concatenation is a powerful technique that enables us to combine and merge lists to create larger and more comprehensive data structures. So, let’s dive into the world of list concatenation!

I. Concatenating Lists using + Operator

One of the simplest ways to concatenate lists is by using the + operator. Let’s consider an example where we have two lists: list1 and list2:

Example Code
list1 = [1, 2, 3] list2 = [4, 5, 6] concatenated_list = list1 + list2 print("The concatenated list is:", concatenated_list)

In this example, we use the + operator to concatenate list1 and list2. The + operator combines the elements of both lists, creating a new list called concatenated_list. The resulting list contains all the elements from list1 followed by all the elements from list2.

Output
The concatenated list is: [1, 2, 3, 4, 5, 6]

II. Concatenating Lists using the extend() Method

Another way to concatenate lists is by using the extend() method. Let’s modify our previous example to showcase the extend() method:

Example Code
list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print("The concatenated list using the extend() method is:", list1)

Above , we use the extend() method on list1 and pass list2 as an argument. The extend() method adds the elements of list2 to the end of list1, effectively concatenating the two lists. The original list1 is modified, and the result is displayed below:

Output
The concatenated list using the extend() method is: [1, 2, 3, 4, 5, 6]

Python Nested Lists: Lists within Lists

In our exploration of Python lists, we’ve covered various aspects of working with single-dimensional lists. Now, let’s take a dive into the Python nested lists. A nested list is a list that contains other lists as its elements. This powerful concept allows us to create complex data structures, representing multidimensional data and hierarchical relationships. So, let’s unravel the potential of nested lists!

I. Creating Nested Lists

To create a nested list, we simply include lists as elements within another list. Let’s consider an example where we have a nested list representing a matrix:

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

In this example, we create a nested list called matrix. Each element of matrix is itself a list representing a row in the matrix. By including lists as elements, we form a two-dimensional structure. The outer list contains three inner lists, each representing a row in the matrix.

II. Accessing Elements in Nested Lists

To access elements in nested lists, we use multiple indices to navigate through the dimensions. Let’s consider our previous matrix example and access specific elements:

Example Code
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("The element at row 1, column 2 is:", matrix[1][2])

In this example, we access the element at row 1 and column 2 of the matrix using matrix[1][2]. The first index 1 refers to the second inner list row 1, and the second index 2 refers to the third element within that inner list column 2. By specifying multiple indices, we can retrieve specific elements within the nested list structure.

Output
The element at row 1, column 2 is: 6

III. Modifying Elements in Nested Lists

Modifying elements in nested lists follows a similar approach to accessing elements. We use multiple indices to navigate and update specific elements. Let’s modify an element in our matrix example:

Example Code
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] matrix[0][1] = 10 print("The updated matrix is:", matrix)

In this example, we modify the element at row 0 and column 1 of the matrix by assigning the value 10 to matrix[0][1]. By specifying the indices, we can navigate to the desired element and update its value. The resulting matrix reflects the modification we made.

Output
The updated matrix is: [[1, 10, 3], [4, 5, 6], [7, 8, 9]]

Throughout this Python helper tutorial, we have taken you on a step-by-step journey, providing clear instructions and practical examples to help you master the art of Python lists. Whether you’re a beginner or already have some experience, we’ve got you covered.

From creating lists using square brackets and commas to converting iterable objects into lists with the list() function, we have explored various ways to create lists in Python. We have also learned how to access and retrieve specific elements using indexing, and how to modify lists by updating elements or using methods like append() and insert(). Sorting lists in ascending or descending order has become a breeze with the sort() method and the sorted() function, and we have discovered how to remove items from lists using methods like del, remove(), and clear().

Furthermore, we have delved into the fascinating realm of list indexing, where we can access and modify elements by referring to their position in the list. We have even explored negative indexing, which allows us to access elements starting from the end of the list. Lastly, we have ventured into the world of list slicing, enabling us to extract subsets of lists based on a range of indices.

Now, armed with these newfound skills, you are ready to unlock the full potential of Python lists and embark on exciting adventures in data manipulation. So, grab your coding hat, embrace the versatility of lists, and let your creativity soar. The possibilities are endless, and the treasures hidden within your lists are waiting to be discovered. Happy coding!

 
Scroll to Top