List¶
List is the most universal and popular data structure in Python. If you're not yet sure which structure you'll need in your project, just use a list - it's relatively easy to migrate from it to something more specialized later.
A list is an ordered mutable collection of objects of arbitrary types. The internal structure of a list is a dynamic array of pointers, meaning that lists store not the objects themselves but references to them, which allows them to contain elements of different types.
a = [] # Creating an empty list
a: list[int] = [10, 20]
b: list[int] = [30, 40]
a.append(50) # Adding a value to the end of the list
b.insert(2, 60) # Inserting a value at a specific index
print(a, b)
a += b
print(f'Add: {a}')
a.reverse()
b = list(reversed(a)) # reversed() returns an iterator, not a list
print(f'Reverse: {a}, {b}')
b = sorted(a) # Returns a new sorted list
a.sort() # Modifies the original list and returns nothing
print(f'Sort: {a}, {b}')
a.clear() # Clearing the list
[10, 20, 50] [30, 40, 60] Add: [10, 20, 50, 30, 40, 60] Reverse: [60, 40, 30, 50, 20, 10], [10, 20, 50, 30, 40, 60] Sort: [10, 20, 30, 40, 50, 60], [10, 20, 30, 40, 50, 60]
s: str = 'A whole string'
list_of_chars: list = list(s)
print(list_of_chars)
list_of_words: list = s.split()
print(list_of_words)
i: int = list_of_chars.index('w') # Returns the index of the first occurrence of the found element or raises a ValueError
print(i)
list_of_chars.remove('w') # Removes the first occurrence of the found element or raises a ValueError
e = list_of_chars.pop(9) # Removes and returns the value located at the index. pop() without an argument will remove and return the last element of the list
print(list_of_chars, e)
['A', ' ', 'w', 'h', 'o', 'l', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'] ['A', 'whole', 'string'] 2 ['A', ' ', 'h', 'o', 'l', 'e', ' ', 's', 't', 'i', 'n', 'g'] r
Can negative indices be used with iterative types?
Yes, they can. A negative index allows counting from the end of a data structure, such as an array or list. This trick is somewhat ambiguous and can lead to errors that might be difficult to track down, which is why, for example, in Golang this quirk was prohibited.