Example 1:

      
          Example 1: Creating a List

fruits = ["apple", "banana", "cherry"]
print(fruits)
          

Example 2:

      
          Example 2: Accessing List Items

print(fruits[1])  # Outputs 'banana'
          

Example 3:

      
          Example 3: Changing List Items
fruits[1] = "blueberry"
print(fruits)  # The list now contains 'blueberry' instead of 'banana'
          

Example 4:

      
          Example 4: Adding List Items (Append)
fruits.append("orange")
print(fruits)  # 'orange' has been added to the end of the list
          

Example 5:

      
          Example 5: Adding List Items (Insert)
fruits.insert(1, "mango")
print(fruits)  # 'mango' is inserted at index 1
          

Example 5:

      
          Example 5: Adding List Items (Insert)
fruits.insert(1, "mango")
print(fruits)  # 'mango' is inserted at index 1
          

Example 6:

      
          Example 6: Removing List Items
fruits.remove("cherry")
print(fruits)  # 'cherry' has been removed from the list
          

Example 7:

      
          Example 7: Removing List Items by Index (pop)
popped_fruit = fruits.pop(2)
print(popped_fruit)  # This will output 'blueberry', which was at index 2
print(fruits)        # The list now has 'blueberry' removed
          

Example 8:

      
          Example 8: Finding the Index of an Item
index_of_apple = fruits.index("apple")
print(index_of_apple)  # Outputs 0
          

Example 9:

      
          Example 9: Sorting a List
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
numbers.sort()
print(numbers)  # Outputs the sorted list
          

Example 10:

      
          Example 10: Reversing a List
numbers.reverse()
print(numbers)  # Outputs the list in reversed order
          
All Examples on lists