List Examples

Creating a list:


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

Output:


            ['apple', 'banana', 'cherry']
        

Accessing elements of a list:


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

Output:


            apple
            banana
            cherry
        

Modifying elements of a list:


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

Output:


            ['apple', 'mango', 'cherry']
        

Adding elements to a list:


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

Output:


            ['apple', 'banana', 'cherry', 'orange']
        

Removing elements from a list:


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

Output:


            ['apple', 'cherry']
        

Iterating over a list:


            fruits = ["apple", "banana", "cherry"]
            for fruit in fruits:
                print(fruit)
        

Output:


            apple
            banana
            cherry
        

Checking if an element exists in a list:


            fruits = ["apple", "banana", "cherry"]
            if "banana" in fruits:
                print("Yes, banana is in the list.")
            else:
                print("No, banana is not in the list.")
        

Output:


            Yes, banana is in the list.