Skip to main content

4.2 - Working With Lists

Lists in Python are ordered collections of items that can hold a variety of object types (e.g., numbers, strings, other lists). They are defined by enclosing elements in square brackets [...], and the elements can be accessed by their index.

Lists are mutable, allowing for modification of their contents. This includes adding, removing, or changing elements. They also support duplicate elements, meaning a list can contain the same value multiple times.

4.2.1 - Creating Lists

Lists in Python are ordered collections that can hold a variety of object types. They are created by enclosing elements in square brackets []:

# An empty list
empty_list = []

# A list of integers
int_list = [1, 2, 3, 4, 5]

# A mixed type list
mixed_list = [1, "hello", 3.14, True]

4.2.2 - Accessing List Elements

List elements can be accessed by their index. Python also supports negative indexing:

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

# Accessing the first element
first_element = my_list[0]

# Accessing the last element using negative indexing
last_element = my_list[-1]

4.2.3 - Slicing Lists

Slicing allows you to get a subset of the list:

# Getting the first three elements
first_three = my_list[:3]

# Getting elements from 2nd to 4th position
slice_middle = my_list[1:4]

# Getting the last two elements
last_two = my_list[-2:]

4.2.4 - Modifying Lists

Lists are mutable, meaning their elements can be changed:

# Changing the first element
my_list[0] = 100

# Changing a slice
my_list[1:3] = [200, 300]

4.2.5 - Adding Elements to Lists

  • .append(element): Adds an element to the end of the list.
  • .insert(index, element): Inserts an element at the specified index.
  • += or .extend(iterable): Extends the list by appending elements from an iterable.

Example:

my_list.append(60)
my_list.insert(1, 15)
my_list += [70, 80]

4.2.6 - Removing Elements from Lists

  • .remove(element): Removes the first occurrence of the element.
  • .pop([index]): Removes and returns the element at the index. If no index is specified, it removes and returns the last element.
  • del list[index]: Removes the element at the specified index.

Example:

my_list.remove(30)
popped_element = my_list.pop(1)
del my_list[0]

4.2.7 - List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable:

# Squaring numbers in a range
squares = [x**2 for x in range(10)]

4.2.8 - Sorting Lists

  • .sort(): Sorts the list in place.
  • sorted(list): Returns a new sorted list.

Example:

my_list = [3, 1, 4, 1, 5, 9, 2]
my_list.sort()
new_sorted_list = sorted(my_list)

4.2.9 - Reversing Lists

  • .reverse(): Reverses the elements of the list in place.
  • reversed(list): Returns an iterator that accesses the given list in the reverse order.

Example:

my_list.reverse()
new_reversed_list = list(reversed(my_list))

4.2.10 - Iterating Over Lists

You can iterate over the elements of a list using a for loop:

for element in my_list:
print(element)

4.2.11 - List Length

To get the number of elements in a list, use the len() function:

length = len(my_list)

4.2.12 - Checking if an Item Exists in a List

To check if an item exists in a list, use the in keyword:

if 1 in my_list:
print("1 is in the list")

4.2.13 - Nested Lists

Lists can contain other lists. This is known as a nested list:

nested_list = [1, 2, [3, 4], [5, 6]]

4.2.14 - Copying Lists

  • .copy(): Creates a shallow copy of the list.
  • list(old_list): Also creates a shallow copy.
  • `import copy; copy.deepcopy(old_list

)`: Creates a deep copy of the list.

Example:

shallow_copy = my_list.copy()
deep_copy = copy.deepcopy(my_list)

4.2.15 - Summary Table of List Methods and Techniques

Method/TechniqueDescriptionExample
Creating ListsDefine a list using square brackets.my_list = [1, 2, 3]
Accessing ElementsAccess elements by their index.element = my_list[0]
Slicing ListsGet a subset of the list.subset = my_list[:2]
Modifying ListsChange the value of list elements.my_list[0] = 10
.append(element)Add an element to the end of the list.my_list.append(4)
.insert(index, element)Insert an element at the specified index.my_list.insert(1, 5)
+= / .extend(iterable)Extend the list by appending elements.my_list += [6, 7]
.remove(element)Remove the first occurrence of the element.my_list.remove(2)
.pop([index])Remove and return the element at the index.popped = my_list.pop()
del list[index]Remove the element at the specified index.del my_list[0]
List ComprehensionsConcise way to create lists.squares = [x**2 for x in range(10)]
.sort()Sorts the list in place.my_list.sort()
sorted(list)Returns a new sorted list.sorted_list = sorted(my_list)
.reverse()Reverses the list in place.my_list.reverse()
reversed(list)Returns a reversed iterator.reversed_list = list(reversed(my_list))
Iterating Over ListsIterate over list elements using a loop.for x in my_list: print(x)
len(list)Get the number of elements in the list.length = len(my_list)
Checking Item ExistenceCheck if an item exists in the list.if 1 in my_list: ...
Nested ListsLists can contain other lists.nested_list = [1, [2, 3]]
.copy()Creates a shallow copy of the list.copy_list = my_list.copy()
copy.deepcopy(list)Creates a deep copy of the list.deep_copy = copy.deepcopy(my_list)