In [2]:
# Creating a list of numbersnumbers = [1, 2, 3, 4, 5]# Creating a list of stringsfruits = ["apple", "banana", "orange"]# Creating a mixed-type listmixed_list = [1, "hello", 3.14, True]# Creating an empty listempty_list = []# Displaying the listsprint(numbers)print(fruits)print(mixed_list)print(empty_list) #clcoding.com[1, 2, 3, 4, 5] ['apple', 'banana', 'orange'] [1, 'hello', 3.14, True] []
In [3]:
# Accessing individual elementsprint(fruits[0]) print(numbers[-1]) # Slicing a listprint(numbers[1:4]) print(fruits[:2]) #clcoding.comapple 5 [2, 3, 4] ['apple', 'banana']
In [4]:
# Modifying elementsfruits[1] = "grape"print(fruits) # Appending elementsfruits.append("kiwi")print(fruits) # Extending a list with another listfruits.extend(["mango"])print(fruits) #clcoding.com['apple', 'grape', 'orange'] ['apple', 'grape', 'orange', 'kiwi'] ['apple', 'grape', 'orange', 'kiwi', 'mango']
In [4]:
# Removing by valuefruits.remove("orange")print(fruits) # Popping by indexpopped_fruit = fruits.pop(1)print(f"Popped fruit: {popped_fruit}") print(fruits) #clcoding.com['apple', 'grape', 'kiwi', 'mango', 'pineapple'] Popped fruit: grape ['apple', 'kiwi', 'mango', 'pineapple']
In [5]:
# Length of a listprint(len(fruits)) # Checking if an element is in a listprint("kiwi" in fruits) # Concatenating listsnew_list = numbers + [6, 7, 8]print(new_list) #clcoding.com4 True [1, 2, 3, 4, 5, 6, 7, 8]
In [6]:
# Iterating through a listfor fruit in fruits: print(f"Fruit: {fruit}")# Enumerating a listfor index, fruit in enumerate(fruits): print(f"Index: {index}, Fruit: {fruit}") #clcoding.comFruit: apple Fruit: kiwi Fruit: mango Fruit: pineapple Index: 0, Fruit: apple Index: 1, Fruit: kiwi Index: 2, Fruit: mango Index: 3, Fruit: pineapple


0 Comments:
Post a Comment