C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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]
print(values)
# Reduce size of list by 2 elements.
values = values[:-2]
print(values)
Output
[10, 20, 30, 40, 50]
[10, 20, 30]
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']
Tip: A special def may help clarify a program that adds padding to a list in this way.
DefPython 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]
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']
[]