Python Lists

Lists are one of the most versatile and widely used data structures in Python. A list is a collection of items, which can be of different types, and is ordered and mutable, meaning you can change its elements after it has been created. In this lesson, we will cover the basics of lists and how to work with them.

Creating Lists

You can create a list in Python by enclosing items in square brackets [] and separating them with commas. For example:

fruits = ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
mixed_list = ['hello', 42, True]

Accessing Elements

You can access elements in a list using indexing. Indexing starts at 0 for the first element and -1 for the last element. For example:

print(fruits[0])  # Output: 'apple'
print(numbers[-1])  # Output: 5

Modifying Elements

You can modify elements in a list by assigning a new value to the desired index. For example:

fruits[1] = 'orange'
print(fruits)  # Output: ['apple', 'orange', 'cherry']

Adding and Removing Elements

You can add elements to a list using the append() method or the insert() method. To remove elements, you can use the remove() method or the pop() method. For example:

fruits.append('banana')
print(fruits)  # Output: ['apple', 'orange', 'cherry', 'banana']

fruits.remove('orange')
print(fruits)  # Output: ['apple', 'cherry']

removed_fruit = fruits.pop(1)
print(removed_fruit)  # Output: 'cherry'
print(fruits)  # Output: ['apple']

Conclusion

Lists are a fundamental part of Python programming, allowing you to store and manipulate collections of data. By understanding how to create, access, modify, add, and remove elements in lists, you can write more powerful and flexible Python programs.



[ Footer Placeholder]