Lists in Python

In Python, lists are a versatile and commonly used data structure that allows you to store an ordered collection of items. Lists can hold items of different data types, including numbers, strings, objects, and even other lists.

Creating a List in Python

In Python, lists are constructed using square brackets [ ], and the items within the list are separated by commas.

Syntax for Creating a List:

  • You define the list with a name.
  • Use square brackets to enclose the list items.
  • Separate the items with commas.

Example:

lists.py
# Creating a list of colors
colors = ["blue", "green", "purple", "yellow", "orange"]
 
# Displaying the list
print(colors)
# Output: ['blue', 'green', 'purple', 'yellow', 'orange']

In this example, each item in the list is a string representing the name of colors. When you print the list, it looks exactly like the list you created.

Creating Different Types of Lists

You can create lists containing different types of data. A list can even be empty.

Examples:

types_of_lists.py
# List with numbers
numbers_list = [1,2,3,4,5,6]
 
# Mixed list with different data types
mixed_list = ['bitch', 7.44, 69, [1, 2, 3, 4]]
 
# Empty list
empty_list = []
 
# Checking the type of the lists
print(type(mixed_list))  # Output: <class 'list'>
print(type(empty_list))  # Output: <class 'list'>
print(type(empty_list))  # Output: <class 'list'>
  • numbers_list contains only numbers.
  • mixed_list contains a string, a float, an integer, and another list.
  • empty_list is an example of an empty list, and its type is still a list.

You can store any item in a list - strings, numbers, objects, or even other lists. The items in a list don't need to be of the same type, meaning a list can be heterogeneous.

Basic List Operations

Python provides various operations to work with lists. You can concatenate lists, repeat them, or check for the presence of an item.

Examples:

list_operations.py
# Creating two lists
list_1 = [1, 3, 5, 7]
list_2 = [2, 4, 6, 8]
 
# Concatenating lists
combined_list = list_1 + list_2
print(combined_list)
# Output: [1, 3, 5, 7, 2, 4, 6, 8]
 
# Repeating a list
repeated_list = list_1 * 3
print(repeated_list)
# Output: [1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]
 
# Comparing two lists
are_equal = list_1 == list_2
print(are_equal)
# Output: False
  • Concatenation: The + operator is used to combine two lists into a new list.
  • Repetition: The * operator repeats the items in the list a specified number of times.
  • Comparison: You can compare two lists using the == operator, which returns True if the lists are identical, and False otherwise.

Membership Operators

You can check whether an item is in a list using the in and not in operators, which return a Boolean value.

Example:

list_items = [1, 3, 5, 7]
 
# Check if an item is in the list
print(5 in list_items)  # Output: True
print(10 in list_items)  # Output: False
  • in operator returns True if the item is present in the list, and False otherwise.

The list() Function

The list() function in Python is used to create a list from a sequence like a string, tuple, or another list. If no sequence is provided, it creates an empty list.

Example:

# Converting a string to a list
question = "How are you?"
string_to_list = list(question)
print(string_to_list)
# Output: ['H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', '?']
 
# Concatenating a list with a string converted to a list
friends = ["e", "n", "i", "v"]
 
# combined = friends + question     # TypeError: can only concatenate list (not "str") to list
combined = friends + list(question)
 
print(combined)
# Output: ['e', 'n', 'i', 'v', 'H', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', '?']
  • Converting a string to a list: The list() function splits the string into its individual characters and creates a list.
  • Concatenating a list with a string: You cannot directly concatenate a string with a list; you must first convert the string to a list.

Indexing and Slicing in Lists

In Python, lists are ordered collections of items. You can access individual items and extract sublists using indexing and slicing techniques.

Indexing

Indexing allows you to access specific elements in a list. The index is an integer value enclosed in square brackets [ ], with indexing starting from 0.

Syntax for Accessing an Item:

list_name[index]

Examples:

# Defining a list of colors
colors = ["red", "green", "blue", "yellow", "orange"]
 
# Accessing items using positive indices
print(colors[0]) # Output: 'red'
print(colors[1]) # Output: 'green'
print(colors[2]) # Output: 'blue'
print(colors[3]) # Output: 'yellow'
print(colors[4]) # Output: 'orange'
 
# Attempting to access an index out of range
# print(colors[9])  # Output: IndexError: list index out of range
  • Positive Indexing: The index 0 refers to the first item, 1 to the second, and so on.
  • IndexError: If you try to access an index that does not exist, Python raises an IndexError.

Negative Indexing: Allows you to access items from the end of the list. The index -1 refers to the last item, -2 to the second-to-last item, etc.

Example:

# Accessing items using negative indices
print(colors[-3])  # Output: 'blue'

Modifying Items

Lists are mutable, meaning their contents can be changed after creation. You can modify the items in a list by assigning new values to specific indices. Additionally, assigning a list to a new variable creates a reference to the same list, not a copy.

Examples:

# Defining a list of cars
cars = ["Ford", "Toyota", "Honda"]
 
# Modifying items in the list
cars[0] = "Chevrolet"  # Changing the first item
print(cars)  # Output: ['Chevrolet', 'Toyota', 'Honda']
 
cars[2] = "Tesla"  # Changing the third item
print(cars)  # Output: ['Chevrolet', 'Toyota', 'Tesla']
 
cars[-1] = "Nissan"  # Changing the last item using negative indexing
print(cars)  # Output: ['Chevrolet', 'Toyota', 'Nissan']

Explanation:

  1. Changing an Item by Positive Index: The first item, "Ford", is replaced with "Chevrolet" using index 0.
  2. Changing an Item by Positive Index: The third item, "Honda", is replaced with "Tesla" using index 2.
  3. Changing an Item by Negative Index: The last item, "Tesla", is replaced with "Nissan" using negative index -1.

Variable Assignment and Modification

When you assign a list to a new variable, both variables refer to the same list object in memory. Changes made through one variable are reflected in the other.

Example:

# Creating a list of cars
cars = ["Ford", "Toyota", "Honda"]
 
# Assigning the list to a new variable
new_cars = cars
 
# Modifying the list through the new variable
new_cars[1] = "BMW"
print(new_cars)  # Output: ['Ford', 'BMW', 'Honda']
print(cars)      # Output: ['Ford', 'BMW', 'Honda']
 
# Further modification
cars[-1] = "Audi"
print(new_cars)  # Output: ['Ford', 'BMW', 'Audi']
print(cars)      # Output: ['Ford', 'BMW', 'Audi']

Variable Assignment: When cars is assigned to new_cars, both variables point to the same list. Therefore, changes made through new_cars are also seen when accessing cars.

Slicing in Python

Slicing is a powerful feature in Python that lets you extract specific portions of a list (or other sequence types like strings and tuples). You achieve this by specifying a start and stop index, and optionally, a step value. The resulting slice includes elements from the start index up to, but not including, the stop index.

Syntax for Slicing:

list_name[start:stop:step]
  • start: The index where the slice begins. If omitted, it defaults to 0 (the beginning of the list).
  • stop: The index where the slice ends. The element at this index is not included in the slice. If omitted, it defaults to the length of the list (the very end).
  • step: The number of indices to jump between elements. If omitted, it defaults to 1 (include every element).

Examples using Positive Indices:

colors = ["red", "orange", "yellow", "green", "blue"]
 
print(colors[1:3])     # Output: ['orange', 'yellow']
print(colors[:3])      # Output: ['red', 'orange', 'yellow']
print(colors[2:])      # Output: ['yellow', 'green', 'blue']
print(colors[1:4:2])   # Output: ['orange', 'green']  (start at 1, go up to 4, take every 2nd element)
print(colors[:])       # Output: ['red', 'orange', 'yellow', 'green', 'blue'] (the whole list)
print(colors[::2])     # Output: ['red', 'yellow', 'blue'] (every other element)

Slicing with Negative Indices

You can also use negative indices for both start and stop. Negative indices count backward from the end of the list, where -1 represents the last element.

print(colors[::-1])     # Output: ['blue', 'green', 'yellow', 'orange', 'red'] (reverses the list)
print(colors[-3:-1])    # Output: ['yellow', 'green'] (start at 3rd from the end, go up to but not including the last)

Built-In Functions Used on Lists

Python provides several built-in functions that you can use with lists. These functions allow you to perform various operations such as finding the length, summing up numbers, and sorting.

FunctionDescription
len()Returns the number of items in the list.
sum()Returns the sum of all numerical items in the list.
max()Returns the maximum value in the list.
min()Returns the minimum value in the list.
any()Returns True if any item in the list is True (or evaluates to True).
all()Returns True if all items in the list are True (or evaluate to True).
sorted()Returns a new list that is a sorted version of the original list. The original list remains unchanged.

Examples

1. len() Function:

colors = ['red', 'blue', 'green', 'yellow', 'orange']
print(len(colors))  # Output: 5
  • The len() function returns the number of items in the colors list.

2. sum() Function:

numbers = [1, 2, 3, 4, 5]
print(sum(numbers))  # Output: 15
  • The sum() function calculates the total of all numerical items in the numbers list.

3. max() and min() Functions:

numbers = [1, 2, 3, 4, 5]
print(max(numbers))  # Output: 5
print(min(numbers))  # Output: 1
  • max() returns the highest value, and min() returns the lowest value in the list.

4. any() Function

print(any([1, 1, 0, 0, 1, 0]))  # Output: True

Explanation:

The any() function checks if at least one element in an iterable (such as a list) is true. It returns True if any element evaluates to True, and False otherwise. In Python, values considered False are:

  • False
  • None
  • Numeric zero (0)
  • Empty sequences (e.g., "", [], ())
  • Empty mappings (e.g., {})

In the example, since there are 1 (which are True), any([1, 1, 0, 0, 1, 0]) returns True.

5. all() Function

print(all([1, 1, 1, 1]))  # Output: True
print(all([1, 0, 1, 1]))  # Output: False

Explanation:

The all() function checks if every element in an iterable is true. It returns True only if all elements evaluate to True. If any element is False, the function returns False.

  • In the first example, all elements are 1, which are True, so all([1, 1, 1, 1]) returns True.
  • In the second example, the presence of 0 (which is False) makes all([1, 0, 1, 1]) return False.

6. sorted() Function:

colors = ['red', 'blue', 'green', 'yellow', 'orange']
colors_sorted_new = sorted(colors)
print(colors_sorted_new)  # Output: ['blue', 'green', 'orange', 'red', 'yellow']
  • The sorted() function returns a new list that is sorted, leaving the original colors list unchanged. In the case of string items in the list, they are sorted based on their ASCII values.

List Methods

Python lists come with a variety of built-in methods that allow you to perform operations like adding, removing, and modifying items.

MethodSyntaxDescription
append()list.append(item)Adds a single item to the end of the list.
count()list.count(item)Counts the number of occurrences of an item in the list.
insert()list.insert(index, item)Inserts an item at a specified index, shifting subsequent items to the right.
extend()list.extend(list2)Extends the list by appending elements from another list.
index()list.index(item)Returns the index of the first occurrence of an item. Raises ValueError if not found.
remove()list.remove(item)Removes the first occurrence of an item. Raises ValueError if not found.
sort()list.sort()Sorts the items of the list in place.
reverse()list.reverse()Reverses the items of the list in place.
pop()list.pop([index])Removes and returns the item at the specified index. Returns the last item if index is omitted.

Examples

1. append() Method:

cities = ["palampur", "dharamshala", "kangra"]
cities.append('una')
print(cities)  # Output: ['palampur', 'dharamshala', 'kangra', 'una']
  • Adds 'una' to the end of the cities list.

2. count() Method:

cities = ["palampur", "dharamshala", "kangra", "kangra"]
print(cities.count('kangra'))  # Output: 2
  • Counts how many times 'kangra' appears in the list.

3. insert() Method:

cities = ["palampur", "dharamshala", "kangra"]
cities.insert(1, 'una')
print(cities)  # Output: ['palampur', 'una', 'dharamshala', 'kangra']
  • Inserts 'una' at index 1.

4. extend() Method:

cities = ["palampur", "dharamshala", "kangra"]
more_cities = ["una", "solan"]
cities.extend(more_cities)
print(cities)  # Output: ['palampur', 'dharamshala', 'kangra', 'una', 'solan']
  • Appends items from more_cities to the end of the cities list.

5. index() Method:

cities = ["palampur", "dharamshala", "kangra"]
print(cities.index('dharamshala'))  # Output: 1
  • Returns the index of the first occurrence of 'dharamshala'.

6. remove() Method:

cities = ["palampur", "dharamshala", "kangra", "dharamshala"]
cities.remove('dharamshala')
print(cities)  # Output: ['palampur', 'kangra', 'dharamshala']
  • Removes the first occurrence of 'dharamshala'.

7. sort() Method:

cities = ["palampur", "dharamshala", "kangra"]
cities.sort()
print(cities)  # Output: ['dharamshala', 'kangra', 'palampur']
  • Sorts the list in alphabetical order.

8. reverse() Method:

cities = ["palampur", "dharamshala", "kangra"]
cities.reverse()
print(cities)  # Output: ['kangra', 'dharamshala', 'palampur']
  • Reverses the order of items in the list.

9. pop() Method:

cities = ["palampur", "dharamshala", "kangra"]
print(cities.pop())  # Output: 'kangra'
print(cities)        # Output: ['palampur', 'dharamshala']
  • Removes and returns the last item from the list. If an index is provided, it removes and returns the item at that index.

Populating Lists with Items

Populating lists in Python is straightforward. You can start with an empty list and use methods like append() or extend() to add items.

Using append() Method:

The append() method adds a single item to the end of the list.

# Create an empty list
countries = []
 
# Add items to the list
countries.append("USA")
countries.append("Canada")
countries.append("Mexico")
 
# Display the list
print(countries)  # Output: ['USA', 'Canada', 'Mexico']

Using extend() Method:

The extend() method adds multiple items to the end of the list from another iterable (like another list).

# Existing list
countries = ["USA", "Canada"]
 
# List to extend
more_countries = ["Mexico", "India"]
 
# Extend the list
countries.extend(more_countries)
 
# Display the list
print(countries)  # Output: ['USA', 'Canada', 'Mexico', 'India']

Traversing Lists

You can use loops to traverse through a list and access each item. The most common way is using a for loop.

Example:

# List of countries
countries = ["USA", "Canada", "Mexico"]
 
# Traverse the list using a for loop
for country in countries:
    print(country)

This will print each country in the list.

Output:

USA
Canada
Mexico

Nested Lists

A nested list is a list within another list. You can create and access nested lists using multiple levels of indexing.

Example of a Nested List:

# Define a nested list
world = [
    ["USA", "Canada", "Mexico"],
    ["Brazil", "Argentina", "Chile"],
    ["China", "Japan", "India"]
]
 
# Access the first sub-list
print(world[0])  # Output: ['USA', 'Canada', 'Mexico']
 
# Access an item within a sub-list
print(world[0][1])  # Output: Canada
 
# Modify an item in a sub-list
world[1][2] = "Peru"
print(world)  # Output: [['USA', 'Canada', 'Mexico'], ['Brazil', 'Argentina', 'Peru'], ['China', 'Japan', 'India']]

Traversing Nested Lists

You can traverse through nested lists using nested for loops.

Example:

# Define a nested list
world = [
    ["USA", "Canada", "Mexico"],
    ["Brazil", "Argentina", "Peru"],
    ["China", "Japan", "India"]
]
 
# Traverse nested lists
for continent in world:
    for country in continent:
        print(country)

This will print each country from each continent in the nested list.

Output

USA
Canada
Mexico
Brazil
Argentina
Peru
China
Japan
India

The del Statement in Python

The del statement in Python is used to remove items from a list based on their index, slices, or even clear the entire list. Unlike the pop() function, which returns the value of the removed item, the del statement does not return any value. Here’s how you can use the del statement:

1. Removing a Single Item

You can use del to remove an item from a list based on its index.

Example:

# Define a list
numbers = [1, 2, 3, 4, 5]
 
# Remove the item at index 0
del numbers[0]
 
# Display the list
print(numbers)  # Output: [2, 3, 4, 5]

In this example, the item 1 at index 0 is removed from the list.

2. Removing a Slice of Items

You can also use del to remove a range of items (a slice) from a list.

Example:

# Define a list
numbers = [1, 2, 3, 4, 5]
 
# Remove items from index 2 to 4 (excluding 4)
del numbers[2:4]
 
# Display the list
print(numbers)  # Output: [1, 2, 5]

In this example, the items 3 and 4 (from index 2 to 4) are removed from the list.

3. Clearing the Entire List

To remove all items from a list, you can use del with a slice that includes all items.

Example:

# Define a list
numbers = [1, 2, 3]
 
# Clear the entire list
del numbers[:]
 
# Display the list
print(numbers)  # Output: []

Here, the entire list is cleared, leaving it empty.

How's article quality?

Last updated on -

Page Contents