PYTHON

Python List: Syntax and Examples [Python Tutorial]

In Python, a list is a built-in data type for storing ordered collections of items. Lists are mutable and can include elements of any type, including booleans, integers, strings, dictionaries, or other lists.

How to Use Python Lists

Python’s list syntax is straightforward. You can use lists in multiple ways: from creating a list to adding, modifying, and removing items.

Creating Lists in Python

The syntax to create a new list in Python requires square brackets ([]). Within the square brackets, you can add values separated by commas to create a list with elements.

fruits = ['apple', 'banana', 'cherry']

You can create (or initialize) an empty list by assigning opening and closing square brackets to a variable. Since lists are mutable, you can add items at any time.

fruits = []

Accessing List Items

You can access elements by referencing their index (i.e., their position in the list) within square brackets. Lists are zero-indexed, so the first item has an index of 0, the second item has an index of 1, etc.

first_fruit = fruits[0]  # Accesses the first item ('apple')

You can also access items from the end of the list using negative indices.

last_fruit = fruits[-1]  # Accesses the last item ('cherry')

Python Add to Lists

Unlike some other programming languages, Python can append to lists because its lists are mutable. Therefore, you can add and remove items from the list at any time. To add list items, you can use list methods like append(), extend(), and insert().

Python’s list append() method adds an item to the end of the list.

fruits.append('date')

With the insert() method, you can insert an item at a specified position.

fruits.insert(1, 'avocado')  # Inserts 'avocado' at index 1

extend() adds all elements of another list (or tuple, string, etc.) you pass along as an argument to the end of the list.

more_fruits = ['fig', 'grape']
fruits.extend(more_fruits)

Modifying List Items

You can update the value of an item in a list by assigning a new value to its index.

fruits = ['apple', 'banana', 'cherry']
fruits[1] = 'blueberry'  # Changes 'banana' to 'blueberry'
print(fruits)  # ['apple', 'blueberry', 'cherry']

Python Removing Items from Lists

You can use list methods like remove(), pop(), and clear() to remove list items. The remove() method removes the first occurrence of an item from the list.

fruits.remove('banana')

The Python list pop() method removes the item at the given position in the list and returns it. Without an argument to specify the index, pop() removes and returns the last item.

last_fruit = fruits.pop()  # Removes and returns the last item

With the clear() method, you can remove all items from the list, resulting in an empty list.

fruits.clear()

When to Use Python Lists

Python lists can help you group elements that belong together. They're particularly useful when the number of elements can change or the elements are of different data types.

Storing and Accessing Ordered Data

Lists maintain the order of elements, making them ideal for tasks like storing sequences or queues.

tasks = ['wake up', 'brush teeth', 'exercise']
print(tasks[1])  # Outputs: brush teeth

Iterating Over Collections

Lists are perfect for iterating through collections, especially when paired with a for loop.

colors = ['red', 'green', 'blue']
for color in colors:
    print(color)

Dynamic Data Storage

Lists can contain duplicates and grow and shrink, making them suitable for dynamic applications like collecting user input.

user_inputs = []
while True:
    user_input = input("Enter a hobby (or type 'done' to finish): ")
    if user_input.lower() == 'done':
        break
    user_inputs.append(user_input)
print(f"Your hobbies are: {user_inputs}")

Using the list() constructor, you can data types like tuples or strings into lists and make them mutable.

# Using the list() constructor
numbers_tuple = (1, 2, 3)
numbers_list = list(numbers_tuple)
print(numbers_list)  # Outputs: [1, 2, 3]

Examples of Python Lists

Lists are highly common in Python programming across industries and platforms.

E-commerce Platforms

An e-commerce platform might use a list to represent a shopping cart.

shopping_cart = ['milk', 'eggs', 'bread']
shopping_cart.append('butter')  # Add an item
shopping_cart.remove('eggs')  # Remove an item
print(shopping_cart)  # Outputs: ['milk', 'bread', 'butter']

Data Science Applications

Data science algorithms and analytics platforms frequently use lists with libraries like numpy and pandas to store and process datasets. Lists can help them filter or transform data to extract useful information.

import numpy as np
import pandas as pd

# List for storing temperatures
temperatures = [20.1, 22.5, 19.8, 25.0]

# Filtering cool days with list comprehension
cool_days = [temp for temp in temperatures if temp < 22]

# Using pandas for data analysis
df = pd.DataFrame({"Temperature": temperatures})
mean_temp = np.mean(temperatures)  # Calculating mean with NumPy

Social Media Platforms

A social media platform might store the IDs of users who have liked a post in a list. This allows for quick access and updates as new likes come in.

post_likes = [101, 204, 305]
post_likes.append(402)  # A new user likes the post
post_likes.remove(101)  # A user unlikes the post
print(post_likes)  # Outputs: [204, 305, 402]

Learn More About Python Lists

Python List Length

To find the length of a list in Python, you can utilize the built-in len() function. This is helpful when iterating through a list or performing operations based on the number of elements.

fruits = ['apple', 'banana', 'cherry']
print(len(fruits))  # Outputs the length of the list: 3

Python Lists of Lists

Lists can store other lists, allowing for multi-dimensional arrays (or nested lists). Such lists of lists in Python are useful for grid representations in games or matrices in scientific computing.

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

Python Slicing Lists

Slicing provides a powerful way to extract a subset of elements from a list. The syntax for slicing uses [start:stop:step], where start is inclusive and stop is exclusive. The optional step defines the interval between items.

first_two = fruits[0:2]  # Gets the first two items
every_other_fruit = fruits[::2]  # Gets every other item

Python Reversing Lists

To reverse a list in Python, you can use the reverse() method or slicing. Using reverse() modifies the original list, while slicing creates a reversed copy of the existing list.

numbers = [1, 2, 3]
numbers.reverse()
print(numbers)  # Outputs: [3, 2, 1]

numbers = [1, 2, 3]
reversed_numbers = numbers[::-1]
print(numbers)  # Outputs: [1, 2, 3]
print(reversed_numbers)  # Outputs: [3, 2, 1]

Python Sorting Lists

You can use the sort() method or the sorted() function to sort lists in Python. While sort() has no return value and modifies the existing list, sorted() creates a sorted copy of the original list.

# Using the sort() method
numbers = [4, 2, 6, 5, 1, 3]
numbers.sort()
print(numbers)  # Output: [1, 2, 3, 4, 5, 6]

# Using the sorted() function
numbers = [4, 2, 6, 5, 1, 3]
sorted_numbers = sorted(numbers)
print(numbers)  # Output: [4, 2, 6, 5, 1, 3]
print(sorted_numbers)  # Output: [1, 2, 3, 4, 5, 6]

By default, Python sorts list elements in ascending order. Using the reverse parameter, however, you can sort them in descending order instead.

# Using the sort() method
numbers = [4, 2, 6, 5, 1, 3]
numbers.sort(reverse=True)
print(numbers)  # Output: [6, 5, 4, 3, 2, 1]

# Using the sorted() function
numbers = [4, 2, 6, 5, 1, 3]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)  # Output: [6, 5, 4, 3, 2, 1]

Python’s list sort() and sorted() also support a key parameter for custom sorting criteria. For example, you can use key with a lambda function to specify how to sort a list of lists in Python.

students = [
  ["Alice", 22, 85],
  ["Bob", 20, 90],
  ["Charlie", 23, 80]

]

# Sorting by grade (index 2)
sorted_students = sorted(students, key=lambda x: x[2])

print(sorted_students) # Outputs: [['Charlie', 23, 80], ['Alice', 22, 85], ['Bob', 20, 90]]

List Comprehension in Python

Python list comprehensions provide a concise syntax for creating lists. Use cases for list comprehensions are deriving a list from another list, filtering items, and applying functions to elements.

# Creating a list of squares for even numbers
squares = [x**2 for x in range(10) if x % 2 == 0]

Python Lists of Dictionaries

Lists can hold dictionaries as elements, providing a way to store complex data structures. Using a list of dictionaries, you can represent the rows in a database table with column names as dict keys.

users = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25}
]

Python List vs. Array

Python lists can store elements of mixed data types. However, this flexibility comes with a trade-off: lists can consume more memory than needed. The array module in Python is great for numerical data of a single type, such as integers or floats.

# List example
mixed_list = [1, "two", 3.0]  # Mixed data types

# Array example
import array
num_array = array.array('i', [1, 2, 3])  # Array of integers

Python List vs. Tuple

Lists are mutable, allowing you to add, remove, or modify elements. Tuples, however, are immutable, which means you can’t change them after creation. This permanence makes tuples ideal for storing constant data, such as configuration settings or coordinates.

# Tuple example (immutable)
coordinates = (10, 20)
# coordinates[0] = 15  # Raises a TypeError

# List example (mutable)
tasks = ["read", "write"]
tasks.append("review")  # Modifies the list

Other Python List Methods

Python has many built-in functions and methods for common operations with list objects. Here's an overview of some additional list methods:

  • index() returns the list index of the first occurrence of the specified item.

letters = ['a', 'b', 'c', 'd', 'e']
index_of_c = letters.index('c')  # 2
  • count() returns the number of times the specified item appears in the list.

numbers = [1, 2, 3, 4, 3, 2, 1, 2, 3]
count_of_2 = numbers.count(2)  # 3
  • copy() creates a shallow copy of the list, which is useful when you want to duplicate a list without changing the original list.

original = [1, 2, 3]
duplicate = original.copy()
duplicate.append(4)
print(original)  # [1, 2, 3]
print(duplicate)  # [1, 2, 3, 4
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH