Introduction

In Python, a list is a collection of items that are ordered and changeable. Lists are one of the most commonly used data structures in Python, and they can contain any type of data, including other lists. This guide will cover the basics of working with lists in Python.

Creating a List

To create a list, you can use square brackets [] and separate the items with commas. For example:

my_list = [1, 2, 3, "apple", "banana"]

This creates a list with five items: the integers 1, 2, and 3, and the strings "apple" and "banana".

Accessing List Items

You can access individual items in a list by using their index. The first item in a list has an index of 0, the second item has an index of 1, and so on. For example:

my_list = [1, 2, 3, "apple", "banana"]
print(my_list[0])  # Output: 1
print(my_list[3])  # Output: apple

You can also use negative indexing to access items from the end of the list. The last item in a list has an index of -1, the second-last item has an index of -2, and so on. For example:

my_list = [1, 2, 3, "apple", "banana"]
print(my_list[-1])  # Output: banana

Modifying Lists

Lists are changeable, which means you can modify them by adding, removing, or changing items. For example:

my_list = [1, 2, 3, "apple", "banana"]
my_list[1] = "orange"  # Change the second item to "orange"
print(my_list)  # Output: [1, 'orange', 3, 'apple', 'banana']

my_list.append("pear")  # Add "pear" to the end of the list
print(my_list)  # Output: [1, 'orange', 3, 'apple', 'banana', 'pear']

del my_list[2]  # Remove the third item from the list
print(my_list)  # Output: [1, 'orange', 'apple', 'banana', 'pear']

List Methods

Python provides several built-in methods for working with lists. Some of the most commonly used methods include: