PYTHON

Python Lists: Syntax, Usage, and Examples

In Python, a list is a data type that consists of an ordered collection of items. Lists can include items (or elements) of any data type, including numbers, strings, dictionaries, functions, and lists.

How to Use Python Lists

Creating Lists

Python lists are created using square brackets ([]). Elements of the list go within the square brackets, separated by commas.

# Creating an empty list
empty_list = []

# Creating a list with elements
fruits = ['apple', 'banana', 'cherry']

Accessing Items

List items are accessible through their index (i.e., their position in the list). Python 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')

Negative indices access items from the end of the list.

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

Adding Items

Items can be added to lists using methods like append(), extend(), and insert().

  • append() adds an item to the end of the list:

    fruits.append('date')
    
  • extend(): Adds all elements of an iterable (e.g., another list) to the end of the list.

    more_fruits = ['fig', 'grape']
    fruits.extend(more_fruits)
    
  • insert(): Inserts an item at a specified position.

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

Removing Items

Items can be removed from lists using methods like remove(), pop(), and clear().

  • remove(): Removes the first occurrence of an item from the list.

    fruits.remove('banana')
    
  • pop(): Removes the item at the given position in the list and returns it. Without a specified index, pop() removes and returns the last item.

    last_fruit = fruits.pop()  # Removes and returns the last item
    
  • clear(): Removes all items from the list, resulting in an empty list.

    fruits.clear()
    

When to Use Python Lists

Python lists are ideal for grouping values that belong together. In particular, lists shine when the number of elements can vary or elements are of different data types.

Storing and Accessing Ordered Data

Lists keep the order of elements, which is crucial for tasks where the sequence of data matters. As an example, consider maintaining a list of tasks in a to-do application.

steps = ['wake up', 'brush teeth', 'exercise', 'have breakfast']
print(f"The second step in the morning routine is to {steps[1]}.")

Iterating Over Collections

Lists are particularly great for storing collections of items for iteration, making them ideal for loops and bulk operations.

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

Flexible Data Aggregation

Lists can grow and shrink, which makes them perfect for scenarios with an undefined volume of data.

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}")

Examples of Python Lists

Lists are highly common in Python applications of any kind. Here are some simple examples:

Managing a Collection of Items

Lists are perfect for managing collections, like a shopping cart in an e-commerce application.

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

Storing Datasets

In data science, lists can store datasets for processing and handling. As an example, consider filtering data based on certain criteria or computing statistical measures.

temperatures = [20.1, 22.5, 19.8, 25.0]
cool_days = [temp for temp in temperatures if temp < 22]
average_temp = sum(temperatures) / len(temperatures)

Learn More About Python Lists

Python Multi-dimensional Lists

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

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

Python Lists vs. Arrays

While both serve to store collections of items, Python lists are more flexible with mixed data types. Arrays (using the array module), on the other hand, are more efficient for numerical data of a single type.

Python Lists vs. Tuples

Unlike lists, tuples are immutable and, therefore, impossible to change after creation. This makes tuples a safer choice for read-only collections of data.

Slicing Lists

Python also supports slicing, which allows you to access a range of items. To slice an array, you need a start and stop index, and optionally a step.

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

Python Sorting Lists

Through sorting, you can organize list items in ascending or descending order. The built-in sort() method is perfect in most cases. By default, sort() sorts the list in ascending order but can change its behavior based on parameters.

# Sorting a list in ascending order
numbers = [4, 2, 6, 5, 1, 3]
numbers.sort()
print(numbers)  # Output: [1, 2, 3, 4, 5, 6]

# Sorting a list in descending order
numbers.sort(reverse=True)
print(numbers)  # Output: [6, 5, 4, 3, 2, 1]

The sorted() function creates a copy of the list in a sorted order, leaving the original list unaffected. Similar to sort(), sorted() defaults to ascending order but can change its behavior with the reverse and key parameters. Unlike sort(), sorted() is a built-in function (not a list method).

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

# Sorting in descending order
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # Output: [6, 5, 4, 3, 2, 1]

Lists and Dictionaries

Lists can hold dictionaries as elements, providing a way to store complex data structures. As an example, consider the rows in a database table with column names as dictionary keys.

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

Python lists are a fundamental tool in your programming arsenal, adaptable to a wide range of tasks from basic data collection to complex data structures and algorithms. Understanding how to effectively leverage lists and

Common List Methods

Python lists come with a set of built-in functions and methods that make it easy to manipulate and interrogate list data. Here's an overview of some of the most commonly used list methods:

  • append() adds a single item to the end of the list:

fruits = ['apple', 'banana']
fruits.append('cherry')  # ['apple', 'banana', 'cherry']
  • The extend() method adds all elements of an iterable (list, tuple, string, etc.) to the end of the list:

numbers = [1, 2]
numbers.extend([3, 4])  # [1, 2, 3, 4]
  • insert() inserts an item at a specified position in the list:

colors = ['red', 'blue']
colors.insert(1, 'green')  # ['red', 'green', 'blue']
  • remove() removes the first occurrence of a specified item from the list:

pets = ['dog', 'cat', 'bird', 'cat']
pets.remove('cat')  # ['dog', 'bird', 'cat']

  • pop() removes the item at the given position in the list, and returns it. Without a specified index, pop() removes and returns the last item in the list.

numbers = [1, 2, 3, 4, 5]
last_number = numbers.pop()  # 5, numbers is now [1, 2, 3, 4]
  • clear() removes all items from the list:

fruits = ['apple', 'banana', 'cherry']
fruits.clear()  # []
  • index() returns the 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
  • sort() sorts the items of the list by changing the list:

numbers = [3, 1, 4, 1, 5]
numbers.sort()  # [1, 1, 3, 4, 5]
  • reverse() reverses the items of the list by changing the list:

numbers = [1, 2, 3, 4, 5]
numbers.reverse()  # [5, 4, 3, 2, 1]

List Comprehension in 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]
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