Python : Lists

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:

Creating a List


You can create a list by enclosing elements in square brackets `[ ]`, separated by commas.


my_list = [1, 2, 3, 4, 5]
 

Accessing Elements


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])  # Out
put: 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)

 

Slicing


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)

 

Modifying Lists


Lists are mutable, so you can change their elements after creation.


my_list[0] = 10
print(my_list)  # Output: [10, 2, 3, 4, 5]

 

List Methods


Python provides several built-in methods to manipulate lists:

  •  append() : Add an element to the end of the list.
  •  extend()  : Add elements from another list to the end of the list.
  •  insert()    : Insert an element at a specified position.
  •  remove() : Remove the first occurrence of a value from the list.
  •  pop()        : Remove and return an element at a specified index (default is the last element).
  •  index()     : Return the index of the first occurrence of a value.
  •  count()     : Return the number of occurrences of a value.
  •  sort()        : Sort the list in ascending order.
  •  reverse()  : Reverse the elements of the list.

Iterating Over Lists


You can iterate over the elements of a list using a `for` loop:


for item in my_list:
    print(item)

 

Checking Membership


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.