Python Data Structures: Lists

In this tutorial, we will dive deep into Python Lists one of its most fundamental built-in data structures. Lists are ordered collections that can contain any type of object. They’re similar to arrays in other languages like C++ and ArrayLists in Java. Let’s create a new list:

# Creating a new list called "my_list" with four elements: an integer, a float, a string, and a boolean value
my_list = [1, 2, 'three', True]

In this example, we’ve created a list called `my_list`. It contains four items of different types an integer (`1`), another integer (`2`), a string (‘three’), and a boolean value (`True`). Lists can contain any type of object.
Lists are ordered collections, meaning that the objects in them have a specific insertion order. This is important to note because you’ll be able to access list items using their indexes or positions within the list:

# Creating a list with three elements: 'one', 'two', and 'three'
my_list = ['one', 'two', 'three']

# Printing the second element in the list, which has an index of 1
print(my_list[1]) # prints 'two'

# Lists can contain any type of object, including strings, integers, and booleans
# This line prints the boolean value `True`
print(True)

In this code snippet, were printing out the second item in `my_list`, which is an integer with a value of 2. The index for accessing items within lists starts at zero (0), so the first item has an index of 0 and the second item has an index of 1.
Lists are also mutable, meaning that you can modify their contents in place by updating or deleting specific list elements:

# Define a list with integer, string, and boolean values
my_list = [1, 2, 3, True]

# Update the third element to be a string with value 'four'
my_list[2] = 'four'

# Print the updated list
print(my_list) # prints [1, 2, 'four', True]

To explore other features of lists, lets dive deeper into some additional techniques that you can use with them. For example, if you want to find items in a list, Python provides several tools for this task:
– The `in` operator allows you to perform membership tests on your list objects:

# Creating a list with different data types
my_list = [1, 2, 'three', True]

# Checking if 'two' is in the list using the 'in' operator
if 'two' in my_list:
    # If 'two' is in the list, print a message
    print('The number two appears in my_list')
else:
    # If 'two' is not in the list, print a different message
    print('The number two does not appear in my_list')

– The `index()` method allows you to find the position of an item within a list. If its found, then its index is returned; otherwise -1 is returned:

# Define a list with different data types
my_list = [1, 2, 'three', True]

# Use the index() method to find the position of an item within the list
# If the item is found, its index is returned; otherwise, -1 is returned
position = my_list.index('two') # returns -1 if not found

# Check if the item was found by comparing the returned index to -1
if position != -1:
    # If the item was found, print its index within the list
    print(f'The string "two" appears at index {position} in my_list')
else:
    # If the item was not found, print a message indicating it
    print('The string "two" does not appear in my_list')

Note that if you want to get a specific item from your list based on an index value, you can use the square bracket notation:

# This script gets a specific item from a list based on an index value and prints the item and its index.

# Define a list
my_list = ['apple', 'banana', 'orange', 'grape', 'mango']

# Define the index value
position = 2

# Get the item at the specified index using square bracket notation
item = my_list[position]

# Print the item and its index
print(f'The string "{item}" appears at index {position} in my_list')

In this example, were getting an item from `my_list` based on its index. The retrieved item is then printed out using a formatted string literal. Note that if you try to get an item from your list using an invalid index value (i.e., one that’s outside the bounds of the list), then Python will raise an IndexError exception:

# This script is attempting to retrieve an item from a list based on its index and print it out using a formatted string literal. However, it contains some errors that need to be corrected.

# First, we need to define the list that we will be working with.
my_list = ['apple', 'banana', 'orange', 'grape', 'mango']

# Next, we need to make sure that the index we are trying to access is within the bounds of the list. We can do this by checking the length of the list and adjusting the index accordingly.
position = 2 # this is within the bounds of the list, as the list has a length of 5 but indexing starts at 0
item = my_list[position] # retrieves the item at index 2, which is 'orange'
print(f'The string "{item}" appears at index {position} in my_list') # prints out the retrieved item using a formatted string literal

# If we try to access an index that is outside the bounds of the list, Python will raise an IndexError exception. To avoid this, we can use a try-except block to catch the exception and handle it appropriately.
try:
    position = 10 # this is outside the bounds of the list, as the list only has 5 items
    item = my_list[position] # this line will raise an IndexError exception
    print(f'The string "{item}" appears at index {position} in my_list') # this line will not be executed if an exception is raised
except IndexError:
    print('The index is out of range for my_list') # prints out a message indicating that the index is out of range for the list

In this example, were getting an item from `my_list` using a position value that’s out of range. If you try to execute this code, then Python will raise an IndexError exception because the requested item doesn’t exist within `my_list`. To avoid these exceptions and handle invalid index values gracefully, you can use a try-except block:

# This script is used to retrieve an item from a list using a position value provided by the user.

# First, we define a list called `my_list` which contains some strings.
my_list = ['apple', 'banana', 'orange', 'grape']

# Next, we use a try-except block to handle any potential errors that may occur.
try:
    # We prompt the user to enter a list index to retrieve.
    position = int(input('Enter the list index to retrieve: '))
    # We check if the position value is within the range of the list.
    if position < 0 or position >= len(my_list):
        # If the position value is invalid, we raise a ValueError.
        raise ValueError("Invalid index")
    # If the position value is valid, we retrieve the item at that index.
    item = my_list[position]
    # We print a message to inform the user of the retrieved item and its index.
    print(f'The string "{item}" appears at index {position} in my_list')
# If any errors occur, we catch them and print a generic error message.
except (ValueError, IndexError) as e:
    print('An error occurred:', str(e))

# Note: This script can handle both ValueError and IndexError exceptions, ensuring that the code does not break if the user enters an invalid index value.

In this example, were using a try-except block to handle invalid input from the user. If an exception is raised due to an invalid index value or if the user enters non-numeric input, then Python will catch it and display an appropriate error message.

SICORPS