Home
Search
Resize ListResize lists with slice syntax and the append method. Reduce and increase the size of lists.
Python
This page was last reviewed on Jan 18, 2023.
Resize list. 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.
Shows a list
Notes on resizing. In addition to resizing, we can clear a list by assigning an empty list. The slice syntax is powerful in Python, and useful here.
Reduce. 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.
Info If the size of the list is less than 2 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.
Shows a list
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]
Resize. 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.
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']
Pad. 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 Here we add, in a range-loop, zeros with the append() method. A special method could be added to perform this logic.
for
range
List append
Def
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]
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.
Info The old list will be lost unless it is stored elsewhere in the program—such as in a local variable.
names = ["Fluffy", "Muffin", "Baby"] print(names) # Clear the list. # ... It now has zero elements. names = [] print(names)
['Fluffy', 'Muffin', 'Baby'] []
A summary. 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.
Slice
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.