List/shaare/pR6E2Q
Lists (list)
Lists are ordered, mutable sequences defined with square brackets []. You can add, remove, or change items after creation.
Characteristics and Use Cases
- Ordered: items maintain position
- Mutable:
.append(),.insert(),.pop(),.remove() - Ideal for storing sequences where order matters and contents change (e.g., list of servers, deployment steps)
Accessing Items and Slicing
- Access single elements with
my_list[index](0-based). Use negative indices likemy_list[-1]for the last item. - Slice with
my_list[start:stop]to get a sub-list fromstartup to (but not including)stop. - Use three-parameter slicing
my_list[start:stop:step]for stepping, e.g.,my_list[::2]selects every other element. - Omitting
startorstopdefaults to the beginning or end of the list respectively, and slicing returns a new list without modifying the original.
servers = ["web01", "web02", "web03"]
mixed_list = ["config.yaml", 8080, True]
for item in mixed_list:
print(type(item))
print(servers[0])
# print(servers[3]) # Commenting this out will raise an IndexError Exception
print(servers[-1])
print(servers[-2])
# Slicing
print(servers[:2]) # Will print only elements at indexes 0 and 1
print(servers[1:]) # Will print only elements at indexes 1 and 2
print(servers[-2:]) # Will print only the second to last and last elements
# Slicing does not alter the original list
print(servers)
# Mutating lists
ports = [80, 443, 8080]
ports.append(5000)
print(ports)
ports.insert(1, 3000)
print(ports)
ports.remove(80)
print(ports)
removed_value = ports.pop(2)
print(ports)
print(removed_value)
# Example to show how mutating lists can lead to side-effects outside of
# the scope of the code that modifies the list.
def mutate_list(l):
l.pop()
new_list = ["a", "b", "c"]
mutate_list(new_list)
print(new_list)
(97)