Python Lists

basic
Published

July 16, 2024

Python lists are arguably the most versatile and frequently used data structure in the language. Their flexibility makes them indispensable for a wide range of programming tasks, from storing simple collections of items to building complex data structures. This post will look into the core functionalities of Python lists, providing clear explanations and illustrative code examples.

What are Python Lists?

Python lists are ordered, mutable (changeable) sequences of items. This means that the elements within a list maintain a specific order, and you can add, remove, or modify elements after the list has been created. Unlike some other data structures, lists can contain elements of different data types within the same list.

Creating Lists:

Lists are defined using square brackets [] and separating elements with commas.

empty_list = []

numbers = [1, 2, 3, 4, 5]

names = ["Alice", "Bob", "Charlie"]

mixed_list = [1, "hello", 3.14, True]

print(empty_list)  # Output: []
print(numbers)     # Output: [1, 2, 3, 4, 5]
print(names)      # Output: ['Alice', 'Bob', 'Charlie']
print(mixed_list) # Output: [1, 'hello', 3.14, True]

Accessing List Elements:

Elements in a list are accessed using their index, starting from 0 for the first element. You can also use negative indexing to access elements from the end of the list, with -1 representing the last element.

my_list = ["apple", "banana", "cherry"]

print(my_list[0])  # Output: apple
print(my_list[1])  # Output: banana
print(my_list[-1]) # Output: cherry

List Slicing:

Slicing allows you to extract a portion of a list. The syntax is list[start:end:step], where start is the starting index (inclusive), end is the ending index (exclusive), and step is the increment between elements.

my_list = [10, 20, 30, 40, 50, 60]

print(my_list[1:4])   # Output: [20, 30, 40]  (elements from index 1 to 3)
print(my_list[::2])   # Output: [10, 30, 50] (every other element)
print(my_list[::-1])  # Output: [60, 50, 40, 30, 20, 10] (reversed list)

Modifying Lists:

Lists are mutable, meaning you can change their contents after creation.

my_list = [1, 2, 3]

my_list.append(4)       # Add to the end
my_list.insert(1, 1.5)  # Insert at a specific index
my_list.extend([5, 6]) # Add multiple elements at the end

my_list.remove(2)       # Remove the first occurrence of 2
del my_list[0]         # Remove element at index 0
popped_element = my_list.pop() # Remove and return the last element


print(my_list)  # Output: [1.5, 3, 4, 5, 6]
print(popped_element) # Output: 6

List Methods:

Python provides numerous built-in methods for working with lists. Some commonly used methods include:

  • len(list): Returns the number of elements in the list.
  • list.count(x): Counts the number of times x appears in the list.
  • list.index(x): Returns the index of the first occurrence of x.
  • list.sort(): Sorts the list in ascending order (in-place).
  • list.reverse(): Reverses the order of elements in the list (in-place).
  • list.copy(): Creates a shallow copy of the list.
my_list = [1, 2, 2, 3, 4]
print(len(my_list))      # Output: 5
print(my_list.count(2))   # Output: 2
print(my_list.index(3))   # Output: 3
my_list.sort()
print(my_list)           # Output: [1, 2, 2, 3, 4]
my_list.reverse()
print(my_list)           # Output: [4, 3, 2, 2, 1]

List Comprehensions:

List comprehensions offer a concise way to create new lists based on existing ones.

numbers = [1, 2, 3, 4, 5]

squares = [x**2 for x in numbers]
print(squares)  # Output: [1, 4, 9, 16, 25]

even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Output: [2, 4]