Skip to main content

Lists

Lists in Python are versatile data structures that allow efficient manipulation and storage of a collection of items. Unlike basic data types like integers, floats, Booleans, and strings, lists can hold multiple items, which can be of different data types, all within a single variable.

Creating Lists

Lists are defined using square brackets [], with elements separated by commas. Each element occupies a position or index within the list.

# Example of a list of strings
fruits = ["apple", "banana", "cherry", "date"]

Accessing List Elements

  • Indexing: Access elements by their position.
    • Zero-based indexing: The first element is at index 0.
    • Negative indexing: The last element is at index -1.
print(fruits[0])   # Output: apple
print(fruits[-1]) # Output: date
  • Slicing: Access a subset of the list.
    • Syntax: list[start:stop] (excluding the stop index).
print(fruits[1:3])  # Output: ['banana', 'cherry']

List Length

Use the len() function to get the number of elements in a list.

print(len(fruits))  # Output: 4

Checking for Element Existence

Use the in keyword to check if an element exists within a list.

print("apple" in fruits)    # Output: True
print("grape" in fruits) # Output: False

Similarities with Strings

  • Both lists and strings are sequences.
  • Support indexing, slicing, and functions like len().
  • Can be iterated over using loops.

Modifying Lists

Unlike strings, lists are mutable, meaning their content can be changed without creating a new list.

Adding Elements

  • append(element): Adds an element to the end of the list.

    fruits.append("elderberry")
    print(fruits) # Output: ['apple', 'banana', 'cherry', 'date', 'elderberry']
  • insert(index, element): Inserts an element at a specified index.

    fruits.insert(0, "fig")
    print(fruits) # Output: ['fig', 'apple', 'banana', 'cherry', 'date', 'elderberry']

Removing Elements

  • remove(element): Removes the first occurrence of an element.

    fruits.remove("banana")
    print(fruits) # Output: ['fig', 'apple', 'cherry', 'date', 'elderberry']
    • Raises a ValueError if the element is not found.
  • pop(index): Removes and returns the element at the specified index.

    removed_fruit = fruits.pop(2)
    print(removed_fruit) # Output: cherry
    print(fruits) # Output: ['fig', 'apple', 'date', 'elderberry']

Modifying Elements

Assign a new value to a specific index.

fruits[1] = "grape"
print(fruits) # Output: ['fig', 'grape', 'date', 'elderberry']

Introduction to Tuples

Tuples are similar to lists but are immutable. Once created, their elements cannot be changed. Tuples are defined using parentheses ().

# Example of a tuple
person = ("John", "A.", "Doe")

When to Use Tuples

  • When the collection of items should not change throughout the program.
  • Useful for representing fixed collections of data, like database records.
  • Often used for function returns that include multiple values.

Accessing Tuple Elements

Works the same way as lists, using indexing and slicing.

print(person[0])    # Output: John
print(person[1:3]) # Output: ('A.', 'Doe')

Unpacking Tuples

You can assign each element of a tuple to a variable.

first_name, middle_initial, last_name = person
print(first_name) # Output: John
print(middle_initial) # Output: A.
print(last_name) # Output: Doe

Tuples in Function Returns

Functions can return multiple values as a tuple.

def split_name(full_name):
parts = full_name.split()
return parts[0], parts[1]

first, last = split_name("Jane Doe")
print(first) # Output: Jane
print(last) # Output: Doe

Iterating Over Lists and Tuples

Using For Loops

Iterate directly over the elements.

animals = ["lion", "zebra", "dolphin", "monkey"]
for animal in animals:
print(animal)

Calculating Totals and Averages

chars = 0
for animal in animals:
chars += len(animal)
print("Total characters:", chars)
print("Average length:", chars / len(animals))

Using Enumerate

Retrieve both the index and the element.

winners = ["Ashley", "Dylan", "Reese"]
for index, person in enumerate(winners):
print("{} - {}".format(index + 1, person))

Output:

1 - Ashley
2 - Dylan
3 - Reese

Example: Formatting Email Addresses

def full_emails(people):
result = []
for email, name in people:
result.append("{} <{}>".format(name, email))
return result

emails = [("alex@example.com", "Alex Diego"), ("shay@example.com", "Shay Brandt")]
print(full_emails(emails))

Output:

['Alex Diego <alex@example.com>', 'Shay Brandt <shay@example.com>']

Caution: Modifying Lists While Iterating

  • Removing elements while iterating can lead to unexpected behavior.
  • If modification is needed, consider iterating over a copy of the list.
# Using a copy to avoid issues
for item in my_list[:]:
if condition(item):
my_list.remove(item)

List Comprehensions

List comprehensions provide a concise way to create lists.

Basic Syntax

new_list = [expression for item in iterable]

Examples

  • Multiples of Seven

    multiples_of_seven = [x * 7 for x in range(1, 11)]
    print(multiples_of_seven)
    # Output: [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
  • Lengths of Strings

    languages = ["Python", "Java", "C++", "Go", "JavaScript"]
    lengths = [len(language) for language in languages]
    print(lengths)
    # Output: [6, 4, 3, 2, 10]
  • Conditional List Comprehension

    divisible_by_three = [x for x in range(1, 101) if x % 3 == 0]
    print(divisible_by_three)
    # Output: [3, 6, 9, ..., 99]

When to Use List Comprehensions

  • For simple transformations and filtering.
  • When you can write the logic in a single, readable line.
  • Improves code conciseness and readability.

When to Use For Loops Instead

  • For complex logic that requires multiple steps.
  • When readability would suffer in a single line.
  • Easier for debugging and maintenance.

List Comprehensions vs. For Loops

Considerations

  • Readability: Choose the method that makes the code clearer.
  • Complexity: For complex operations, prefer for loops.
  • Performance: List comprehensions can be faster in some cases.

Example: Updating Invoice Status

  • Using For Loop

    for invoice in invoices:
    if invoice.age > 30 and not invoice.paid:
    invoice.status = "past due"
  • Using List Comprehension

    past_due = [i for i in invoices if i.age > 30 and not i.paid]
    for invoice in past_due:
    invoice.status = "past due"
  • Recommendation: Use for loops for clarity in complex operations.