C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Reduce. 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.
Based on: Python 3 Python program that reduces size values = [10, 20, 30, 40, 50] print(values) # Reduce size of list by 2 elements. values = values[:-2] print(values) Output [10, 20, 30, 40, 50] [10, 20, 30]
Resize. 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"] print(letters) # Resize list to two elements at the start. letters = letters[:2] print(letters) Output ['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. 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.
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): numbers.append(0) print(numbers) Output [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"] print(names) # Clear the list. # ... It now has zero elements. names = [] print(names) Output ['Fluffy', 'Muffin', 'Baby'] []
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. But to add new elements (to grow a list) we can use append() in a loop.