Here are 8 examples of Python lists along with detailed explanations of each code snippet:
Example 1: Creating an empty Python list
my_list = []
print(my_list)
Explanation:
- We create an empty list named
my_listusing square brackets[]. - We then print the list, which will output an empty list
[].
Output:
[]
Example 2: Creating a list with elements
fruits = ["apple", "banana", "orange", "grape"]
print(fruits)
Explanation:
- We create a list named
fruitscontaining four string elements: "apple", "banana", "orange", and "grape". - We print the list.
Output:
['apple', 'banana', 'orange', 'grape']
Example 3: Accessing elements of a list
fruits = ["apple", "banana", "orange", "grape"]
print(fruits[0])
print(fruits[2])
Explanation:
- We access individual elements of the
fruitslist using their indices. Remember, indexing in Python starts from 0. -
fruits[0]will print the first element, "apple". -
fruits[2]will print the third element, "orange".
Output:
apple
orange
Example 4: Modifying elements of a list
fruits = ["apple", "banana", "orange", "grape"]
fruits[1] = "kiwi"
print(fruits)
Explanation:
- We modify the second element of the
fruitslist by assigning a new value tofruits[1]. - After modification, the list will contain "kiwi" instead of "banana".
Output:
['apple', 'kiwi', 'orange', 'grape']
Example 5: Appending elements to a list
fruits = ["apple", "banana", "orange", "grape"]
fruits.append("mango")
print(fruits)
Explanation:
- We use the
append()method to add a new element, "mango", to the end of thefruitslist. - The
append()method modifies the list in place.
Output:
['apple', 'banana', 'orange', 'grape', 'mango']
Example 6: Removing elements from a list
fruits = ["apple", "banana", "orange", "grape"]
removed_fruit = fruits.pop(1)
print(fruits)
print("Removed:", removed_fruit)
Explanation:
- We use the
pop()method to remove an element from thefruitslist at index 1 (i.e., the second element, "banana"). - The
pop()method returns the removed element, which we store in the variableremoved_fruit. - We print the modified
fruitslist and the removed element.
Output:
['apple', 'orange', 'grape']
Removed: banana
Example 7: Slicing a list
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])
Explanation:
- We use slicing to create a sublist of
numberscontaining elements from index 1 up to, but not including, index 4. - The slice
numbers[1:4]will include elements at indices 1, 2, and 3.
Output:
[2, 3, 4]
Example 8: Concatenating lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)
Explanation:
- We concatenate two lists,
list1andlist2, using the+operator. - The resulting
combined_listcontains elements from bothlist1andlist2.
Output:
[1, 2, 3, 4, 5, 6]
These examples demonstrate various operations that can be performed on Python lists, including creation, modification, access, addition, removal, slicing, and concatenation.
Top comments (0)