List example practice
Creating a list of numbers and printing it:
numbers = [1, 2, 3, 4, 5]
print(numbers)
Output:
Creating a list of strings and printing it:
fruits = ["apple", "banana", "cherry", "orange"]
print(fruits)
Output:
Creating a mixed list and printing it:
mixed_list = [1, "apple", True, 3.14]
print(mixed_list)
Output:
Accessing elements of a list by index:
fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[0]) # Output: "apple"
print(fruits[2]) # Output: "cherry"
Accessing elements of a list by negative index:
fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[-1]) # Output: "orange"
print(fruits[-2]) # Output: "cherry"
Slicing a list to get a range of elements:
fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[1:3]) # Output: ["banana", "cherry"]
Slicing a list to get elements from a starting index to the end:
fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[2:]) # Output: ["cherry", "orange"]
Slicing a list to get elements from the beginning to an ending index:
fruits = ["apple", "banana", "cherry", "orange"]
print(fruits[:2]) # Output: ["apple", "banana"]
Modifying elements of a list by index:
fruits = ["apple", "banana", "cherry", "orange"]
fruits[1] = "kiwi"
print(fruits) # Output: ["apple", "kiwi", "cherry", "orange"]
Modifying a range of elements of a list using slicing:
fruits = ["apple", "banana", "cherry", "orange"]
fruits[1:3] = ["kiwi", "melon"]
print(fruits) # Output: ["apple", "kiwi", "melon", "orange"]
Adding a new element to the end of a list using append():
fruits = ["apple", "banana", "cherry", "orange"]
fruits.append("pear")
print(fruits) # Output: ["apple", "banana", "cherry", "orange", "pear"]
Adding multiple elements to the end of a list using the + operator:
fruits = ["apple", "banana", "cherry", "orange"]
fruits += ["pear", "grape"]
print(fruits) # Output: ["apple", "banana", "cherry", "orange", "pear", "grape"]
I hope these examples help you understand how to work with lists in Python!
for the Next step Click here