Skip to main content

1. What is a List?

  • A list is a collection of items that are ordered, mutable (changeable), and allow duplicate elements.
  • Lists are one of the most versatile data structures in Python.
  • Lists are defined using square brackets [].
Example:

2. List Operations

1. Accessing Elements

  • Use indexing to access individual elements in a list.
  • Python uses zero-based indexing (the first element has index 0).
Example:

2. Slicing

  • Extract a sublist using a range of indices.
  • Syntax: list[start:stop:step]
Example:

3. Modifying Elements

  • Lists are mutable, so you can change their elements.
Example:

4. Adding Elements

  • Use append() to add an element to the end of the list.
  • Use insert() to add an element at a specific position.
  • Use extend() to add multiple elements from another list.
Examples:

5. Removing Elements

  • Use remove() to remove the first occurrence of a value.
  • Use pop() to remove an element at a specific index (or the last element if no index is provided).
  • Use del to delete an element or a slice of elements.
  • Use clear() to remove all elements from the list.
Examples:

6. Finding Elements

  • Use index() to find the index of the first occurrence of a value.
  • Use in to check if an element exists in the list.
Examples:

7. Sorting

  • Use sort() to sort the list in place (modifies the original list).
  • Use sorted() to return a new sorted list (does not modify the original list).
Examples:

8. Reversing

  • Use reverse() to reverse the list in place.
Example:

9. Length

  • Use len() to find the number of elements in a list.
Example:

3. List Comprehensions

  • A concise way to create lists using a single line of code.
  • Syntax: [expression for item in iterable if condition]
Examples:

4. Nested Lists

  • A list can contain other lists, creating a multi-dimensional structure.
Example:

5. Additional Examples

  • Creating a List:
  • Adding Elements:
  • Removing Elements:
  • Sorting:
  • List Comprehension:

6. Best Practices

  • Use list comprehensions for concise and readable code.
  • Avoid modifying a list while iterating over it.
  • Use append() instead of + for adding elements to a list (more efficient).