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_list
using 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
fruits
containing 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
fruits
list 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
fruits
list 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 thefruits
list. - 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 thefruits
list 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
fruits
list 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
numbers
containing 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,
list1
andlist2
, using the+
operator. - The resulting
combined_list
contains elements from bothlist1
andlist2
.
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)