Lists are one of the most commonly used data structures in Python. They are versatile and can hold a collection of items, such as integers, strings, or even other lists. Lists are mutable, meaning you can change their elements after they have been created. Here's a rundown of the basics:
You can create a list by enclosing elements in square brackets `[ ]`, separated by commas.
my_list = [1, 2, 3, 4, 5]
You can access elements of a list using indexing. Python uses 0-based indexing, meaning the first element has an index of 0.
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: 3
You can also use negative indexing to access elements from the end of the list:
print(my_list[-1]) # Output: 5 (last element)
print(my_list[-2]) # Output: 4 (second to last element)
You can also extract a sublist (slice) from a list using slicing notation, which has the form `[start:stop:step]`.
print(my_list[1:4]) # Output: [2, 3, 4] (elements from index 1 to 3)
print(my_list[:3]) # Output: [1, 2, 3] (elements from start to index 2)
print(my_list[2:]) # Output: [3, 4, 5] (elements from index 2 to end)
print(my_list[::2]) # Output: [1, 3, 5] (every second element)
Lists are mutable, so you can change their elements after creation.
my_list[0] = 10
print(my_list) # Output: [10, 2, 3, 4, 5]
Python provides several built-in methods to manipulate lists:
You can iterate over the elements of a list using a `for` loop:
for item in my_list:
print(item)
You can check if an element is present in a list using the `in` operator:
if 3 in my_list:
print("3 is in the list")
This covers the basics of lists in Python.