
Building Lists with Python: Append
Building Lists with Python: Append
In Python, adding items to a list is a common task. The language provides various methods and operators to assist with this operation. One such method is .append(), which adds items to the end of an existing list object. It is also used in a for loop to programmatically populate lists.
Working with .append()
Let’s explore how to work with .append() using examples and code snippets:
Example 1: Adding Items to a List Using .append()
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]Example 2: Populating Lists Using .append() and a for Loop
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for number in numbers:
squared_numbers.append(number ** 2)
print(squared_numbers) # Output: [1, 4, 9, 16, 25]Example 3: Using List Comprehensions Instead of .append()
numbers = [1, 2, 3, 4, 5]
squared_numbers = [number ** 2 for number in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]Working with .append() in Other Data Structures
Apart from regular lists, .append() can be used with other data structures like array.array() and collections.deque(). Let's see how to use .append() with these data structures:
Example 4: Using .append() with array.array()
import array
arr = array.array('i', [1, 2, 3])
arr.append(4)
print(arr) # Output: array('i', [1, 2, 3, 4])Example 5: Using .append() with collections.deque()
from collections import deque
d = deque([1, 2, 3])
d.append(4)
print(d) # Output: deque([1, 2, 3, 4])Conclusion
In this tutorial, you learned how to use .append() to add items to lists, populate lists using a for loop, replace .append() with list comprehensions, and work with .append() in array.array() and collections.deque(). You can explore and practice these examples to strengthen your understanding of .append() in Python.
