Python Introduction | Lists, Tuples, Ranges, Sets, and Dictionaries | Sequence Features
Containers such as lists are useful because they handle multiple values together. Lists also provide operations for adding and removing elements.
Some operations are available only for mutable lists. Others are common to sequence types such as lists, tuples, and ranges.
Adding an Element
list.append(value)
Adds a value to the end of a list.
Inserting an Element at an Index
list.insert(index, value)
Inserts a value at the specified index.
Removing a Value
list.remove(value)
Removes the specified value from a list.
Removing an Element at an Index
del list[index]
Removes the element at the specified index. Do not write parentheses after del.
Adding, inserting, and removing elements modify a container, so they are available for lists but not for immutable tuples or ranges.
Concatenating Containers
variable = container + container
Use + to concatenate lists or tuples. Ranges do not support this operation.
Repeating a Container
variable = container * integer
Creates a container whose values are repeated the specified number of times.
[1, 2, 3] * 3
↓
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Extracting a Range of Elements
variable = container[start:end]
Returns elements from the starting index up to, but not including, the ending index. For example, [2:5] returns elements at indexes 2, 3, and 4.
Checking Whether a Value Exists
value in container
value not in container
These expressions return a Boolean value. in returns True when the container includes the value. not in returns True when it does not.
Obtaining the Number of Elements
variable = len(container)
Returns the number of stored values as an integer.
Obtaining the Maximum and Minimum Values
variable = max(container)
variable = min(container)
Returns the largest or smallest stored value.
The following example modifies and prints a list.
arr = ['hello','bye']
arr.append('finish!')
arr.insert(1, 'welcome')
arr.remove('bye')
for n in arr:
print(n)