What is a List in Python

In Python, a list is a versatile and mutable data structure used to store a collection of elements. It is defined by square brackets [] and elements within separated by commas. Lists can contain elements of different data types (integers, strings, floats, etc.) and can be nested, allowing lists within lists.

Python List of Lists

In Python, a list can contain elements of any data type, including other lists. When a list contains other lists as its elements, it creates a nested or multi-dimensional list. These are often referred to as lists of lists.

Here's an example of a Python list of lists:

list_of_lists = [
    [1, 2, 3],
    ['a', 'b', 'c'],
    [True, False, True]
]

In this example, list_of_lists is a list containing three inner lists. Each inner list represents a row or a collection of elements.

You can access elements within a list of lists using indexing. For instance:

print(list_of_lists[0])  # Output: [1, 2, 3]
print(list_of_lists[1][2])  # Output: 'c'

The first index [1] accesses the second inner list (['a', 'b', 'c']), and the second index [2] accesses the third element within that list ('c').

You can also modify elements within the list of lists using indexing and assignment:

list_of_lists[2][1] = True
print(list_of_lists)  # Output: [[1, 2, 3], ['a', 'b', 'c'], [True, True, True]]

This modifies the second element in the third inner list from False to True.

List of lists are commonly used to represent matrices, tables, or multi-dimensional data structures where elements are organized in rows and columns or structured hierarchically. They are very flexible and allow for complex data representation in Python.

append() Method

In Python, the append() method is used to add a single element to the end of a list. It's a simple way to modify a list by adding an item at the end.

Here's a straightforward example:

my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list)  # Output: [1, 2, 3, 4, 5]

In this example, the append() method adds the integer 5 to the end of the my_list list.

Remember, append() adds only one element at a time. If you want to add multiple elements from another list, you can use the extend() method:

my_list = [1, 2, 3]
another_list = [4, 5, 6]

my_list.extend(another_list)
print(my_list)  # Output: [1, 2, 3, 4, 5, 6]

The extend() method adds all the elements from another_list to the end of my_list.

Both append() and extend() modify the original list in place and do not return a new list. If you want to create a new list with appended elements, you can use concatenation or list comprehension:

my_list = [1, 2, 3]
new_element = 4

new_list = my_list + [new_element]  # Concatenation
print(new_list)  # Output: [1, 2, 3, 4]

This uses the + operator to create a new list by combining the original list with the new element.

Keep in mind that append() and extend() are useful for adding elements to the end of a list and are handy when you want to modify the list directly.

Remove an Item From a List

In Python, there are various ways to remove items from a list based on specific requirements:

  • Using remove() method: If you know the value of the element you want to remove, you can use the remove() method. It removes the first occurrence of the specified value.
my_list = [1, 2, 3, 4, 3]
my_list.remove(3)
print(my_list)  # Output: [1, 2, 4, 3]
  • Using pop() method: If you know the index of the item you want to remove, you can use the pop() method. It removes the item at the specified index and returns its value.
my_list = [1, 2, 3, 4]
removed_item = my_list.pop(2)  # Removes the item at index 2 (value: 3)
print(my_list)  # Output: [1, 2, 4]
print(removed_item)  # Output: 3
  • Using del statement: The del statement is used to remove an item or a slice from a list based on the index or slice specified.
my_list = [1, 2, 3, 4]
del my_list[1]  # Removes the item at index 1 (value: 2)
print(my_list)  # Output: [1, 3, 4]
  • Using slicing: You can also use slicing to remove elements from a list by creating a new list that excludes the elements you want to remove.
my_list = [1, 2, 3, 4]
my_list = my_list[:2] + my_list[3:]  # Removes the item at index 2 (value: 3)
print(my_list)  # Output: [1, 2, 4]

Length of a List

In Python, you can find the length of a list (i.e., the number of elements in the list) using the len() function. The len() function returns the number of items in a container, such as a list, tuple, string, dictionary, etc.

Here's an example of how to find the length of a list:

my_list = [1, 2, 3, 4, 5]
length_of_list = len(my_list)
print(length_of_list)  # Output: 5

In this example, the len() function is used to calculate the number of elements in the my_list list, and the result is stored in the variable length_of_list. The output will be 5, which represents the number of elements in the list.

Is It an Empty List

In Python, you can check if a list is empty by evaluating its boolean value or by using the len() function to determine its length.

You can directly check if a list is empty by evaluating its boolean value. An empty list evaluates to False in a boolean context, while a non-empty list evaluates to True.

Here's an example:

my_list = []

if not my_list:
    print("List is empty")
else:
    print("List is not empty")

If [object Object] is empty, it will print "List is empty"; otherwise, if it contains elements, it will print "List is not empty".

List Sorting

You can sort a list using various methods. The primary methods to sort a list are using the sort() method or the sorted() function.

Using the sort() Method

The sort() method sorts the list in place, modifying the original list.

Example:

my_list = [4, 2, 7, 1, 9]
my_list.sort()
print(my_list)  # Output: [1, 2, 4, 7, 9]

This sorts the my_list in ascending order.

To sort the list in descending order, you can use the reverse=True argument in the sort() method:

my_list = [4, 2, 7, 1, 9]
my_list.sort(reverse=True)
print(my_list)  # Output: [9, 7, 4, 2, 1]

Using the sorted() Function

The sorted() function creates a new sorted list without modifying the original list.

Example:

my_list = [4, 2, 7, 1, 9]
sorted_list = sorted(my_list)
print(sorted_list)  # Output: [1, 2, 4, 7, 9]

Similarly, you can use the reverse=True argument with sorted() to sort the list in descending order:

my_list = [4, 2, 7, 1, 9]
sorted_list_desc = sorted(my_list, reverse=True)
print(sorted_list_desc)  # Output: [9, 7, 4, 2, 1]

Both sort() and sorted() methods allow you to sort lists containing various data types like integers, floats, strings, etc.

How to Reverse a List in Python

In Python, you can reverse a list using various methods.

Using the reverse() Method:

The reverse() method reverses the elements of the list in place, modifying the original list.

Example:

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)  # Output: [5, 4, 3, 2, 1]

Using Slicing Notation:

You can also reverse a list by using slicing notation ([::-1]). This method doesn't modify the original list but creates a new reversed list.

Example:

my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list)  # Output: [5, 4, 3, 2, 1]

Using the reversed() Function:

The reversed() function returns an iterator that allows you to iterate through the list in reverse order. You can convert this iterator to a list using list().

Example:

my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)  # Output: [5, 4, 3, 2, 1]

Index of a List Element

In Python, to find the index of a particular element in a list, you can use the index() method. This method returns the index of the first occurrence of the specified element in the list.

Here's an example demonstrating how to use index():

my_list = ['apple', 'banana', 'orange', 'banana']

index = my_list.index('banana')
print(index)  # Output: 1

In this example, my_list.index('banana') returns 1 because the first occurrence of 'banana' is at index 1 in the list.

If the element you're searching for is not present in the list, calling index() will result in a ValueError. To avoid this error, you can first check if the element exists in the list using the in keyword:

my_list = ['apple', 'banana', 'orange', 'banana']

element = 'grape'
if element in my_list:
    index = my_list.index(element)
    print(f"Index of '{element}' is {index}")
else:
    print(f"'{element}' not found in the list")

List Filtering

You can filter elements from a list based on a specific condition using various methods such as list comprehensions, the filter() function, or lambda functions combined with filter().

Using List Comprehensions:

List comprehensions provide a concise way to create lists by filtering elements from an existing list that satisfy a certain condition.

Example:

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

# Filtering even numbers from my_list
even_numbers = [x for x in my_list if x % 2 == 0]
print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Using the filter() Function:

The filter() function allows you to create an iterator that filters elements based on a given function.

Example using a lambda function:

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

# Filtering even numbers using filter() and lambda function
even_numbers = list(filter(lambda x: x % 2 == 0, my_list))
print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Using a Custom Function with filter():

You can also use a custom function with filter() to perform the filtering based on the defined condition.

Example:

def is_positive(num):
    return num > 0

my_list = [-2, -1, 0, 1, 2, 3]

positive_numbers = list(filter(is_positive, my_list))
print(positive_numbers)  # Output: [1, 2, 3]
Profile picture for user Sarah Chen

The only author and editor of all pages on the site. Most of what I write about is based on years of book reading on the topic.

Updated: 15 March 2024