A list can be manipulated in many ways. To resize a list, we can use slice syntax. Or we can invoke append()
to expand the list's element count.
In addition to resizing, we can clear a list by assigning an empty list. The slice syntax is powerful in Python, and useful here.
To start, we use a slice to reduce the size of a list. Here we resize the list so that the last 2 elements are eliminated.
values = [10, 20, 30, 40, 50] print(values) # Reduce size of list by 2 elements. values = values[:-2] print(values)[10, 20, 30, 40, 50] [10, 20, 30]
Here we use slice again to reduce to a certain element count. This will not add new elements to the end of a list to expand it—we must use append()
to do that.
letters = ["x", "y", "z", "a", "b"] print(letters) # Resize list to two elements at the start. letters = letters[:2] print(letters)['x', 'y', 'z', 'a', 'b'] ['x', 'y']
New elements can be added to the end of a list to pad it. This is necessary when a list is too small, and a default value is needed for trailing elements.
append()
method. A special method could be added to perform this logic.numbers = [1, 1, 1, 1] # Expand the list up to 10 elements with zeros. for n in range(len(numbers), 10): numbers.append(0) print(numbers)[1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
When a list must be cleared, we do not need to change it at all. We can reassign the list reference (or field) to an empty list.
names = ["Fluffy", "Muffin", "Baby"] print(names) # Clear the list. # ... It now has zero elements. names = [] print(names)['Fluffy', 'Muffin', 'Baby'] []
Lists are mutable sequence types. This makes them easy to change, to expand and shrink in size. To resize a list, slice syntax is helpful.