Python list

Lists are versatile data structures in Python that allow you to store and manipulate collections of items. Here's a demonstration of basic list operations including appending, indexing, and slicing:

  • Appending to a List:
  • You can add elements to the end of a list using the "append()" method.

    fruits = ['apple', 'banana', 'orange']
    fruits.append('grape')
    print(fruits)  # Output: ['apple', 'banana', 'orange', 'grape']
  • Indexing a List:
  • You can access individual elements of a list using their index. Indexing is 0-based, meaning the first element is at index 0, the second at index 1, and so on.

    fruits = ['apple', 'banana', 'orange']
    print(fruits[0])  # Output: 'apple'
    print(fruits[1])  # Output: 'banana'
  • Slicing a List:
  • Slicing allows you to extract a portion of a list by specifying start and end indices. The slice includes elements from the start index up to (but not including) the end index.

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    subset = numbers[2:6]
    print(subset)  # Output: [3, 4, 5, 6]

    You can also omit the start or end index to slice from the beginning or until the end of the list, respectively.

    subset_start = numbers[:5]   # Slice from the beginning to index 4
    subset_end = numbers[5:]     # Slice from index 5 to the end
  • Negative Indexing:
  • You can use negative indices to count from the end of the list. "-1" refers to the last element, "-2" to the second-to-last, and so on.

    fruits = ['apple', 'banana', 'orange']
    last_fruit = fruits[-1]  # 'orange'
    second_last_fruit = fruits[-2]  # 'banana'
  • Modifying List Elements:
  • You can modify list elements by assigning new values to specific indices.

    numbers = [1, 2, 3, 4, 5]
    numbers[2] = 10
    print(numbers)  # Output: [1, 2, 10, 4, 5]

These basic list operations—appending, indexing, and slicing—are essential for working with lists and are foundational skills in Python programming.