In [2]:
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# Creating a list of strings
fruits = ["apple", "banana", "orange"]
# Creating a mixed-type list
mixed_list = [1, "hello", 3.14, True]
# Creating an empty list
empty_list = []
# Displaying the lists
print(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 elements
print(fruits[0])
print(numbers[-1])
# Slicing a list
print(numbers[1:4])
print(fruits[:2])
#clcoding.com
apple 5 [2, 3, 4] ['apple', 'banana']
In [4]:
# Modifying elements
fruits[1] = "grape"
print(fruits)
# Appending elements
fruits.append("kiwi")
print(fruits)
# Extending a list with another list
fruits.extend(["mango"])
print(fruits)
#clcoding.com
['apple', 'grape', 'orange'] ['apple', 'grape', 'orange', 'kiwi'] ['apple', 'grape', 'orange', 'kiwi', 'mango']
In [4]:
# Removing by value
fruits.remove("orange")
print(fruits)
# Popping by index
popped_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 list
print(len(fruits))
# Checking if an element is in a list
print("kiwi" in fruits)
# Concatenating lists
new_list = numbers + [6, 7, 8]
print(new_list)
#clcoding.com
4 True [1, 2, 3, 4, 5, 6, 7, 8]
In [6]:
# Iterating through a list
for fruit in fruits:
print(f"Fruit: {fruit}")
# Enumerating a list
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
#clcoding.com
Fruit: apple Fruit: kiwi Fruit: mango Fruit: pineapple Index: 0, Fruit: apple Index: 1, Fruit: kiwi Index: 2, Fruit: mango Index: 3, Fruit: pineapple