Python Resize List: Slice and AppendResize lists with slice syntax and the append method. Reduce and increase the size of lists.
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. We can clear a list by assigning an empty list.List
To start, we use a slice to reduce the size of a list. We resize the list so that the last two elements are eliminated. If the size of the list is less than two elements, we will end up with an empty list (no Error is caused).
Negative size: The second argument of a slice is the size of the slice. When negative, this is relative to the current size.
Python program that reduces size
values = [10, 20, 30, 40, 50]
# Reduce size of list by 2 elements.
values = values[:-2]
[10, 20, 30, 40, 50]
[10, 20, 30]
Sometimes we know the target size of the list. 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.
Note: In these slice examples, the first argument is omitted because it is implicit. When omitted, a start of zero is assumed.
Python program that resizes list
letters = ["x", "y", "z", "a", "b"]
# Resize list to two elements at the start.
letters = letters[:2]
['x', 'y', 'z', 'a', 'b']
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. Here we add, in a range-loop, zeros with the append() method.
Tip: A special def may help clarify a program that adds padding to a list in this way.Def
Python program that pads list with zeros
numbers = [1, 1, 1, 1]
# Expand the list up to 10 elements with zeros.
for n in range(len(numbers), 10):
[1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
Clear. 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. The old list will be lost unless it is stored elsewhere in the program.
Python program that clears list
names = ["Fluffy", "Muffin", "Baby"]
# Clear the list.
# ... It now has zero elements.
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. But to add new elements (to grow a list) we can use append() in a loop.While
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.