Python Lists
Lists are one of the 4 data types in Python used to store collections of data.
# List: ordered collection of items enclosed in square brackets
['John', 'Peter', 'Debora', 'Charles']
Getting values with indexes
# Access list elements using index (0-based, first element is index 0)
furniture = ['table', 'chair', 'rack', 'shelf']
furniture[0] # Returns first element: 'table'
'table'
furniture[1]
'chair'
furniture[2]
'rack'
furniture[3]
'shelf'
Negative indexes
# Negative index: access elements from the end of the list
furniture = ['table', 'chair', 'rack', 'shelf']
furniture[-1] # Returns last element: 'shelf'
'shelf'
furniture[-3]
'chair'
f'The {furniture[-1]} is bigger than the {furniture[-3]}'
'The shelf is bigger than the chair'
Sign in to answer this quiz and track your learning progress
furniture[-1] return if furniture = ['table', 'chair', 'rack', 'shelf']?'table''shelf'['shelf']IndexErrorGetting sublists with Slices
# Slicing: get sublist using [start:end] syntax (end is exclusive)
furniture = ['table', 'chair', 'rack', 'shelf']
furniture[0:4] # Returns elements from index 0 to 3 (4 excluded)
['table', 'chair', 'rack', 'shelf']
furniture[1:3]
['chair', 'rack']
furniture[0:-1]
['table', 'chair', 'rack']
# Slice from beginning: omit start index (defaults to 0)
furniture[:2] # Returns first two elements
['table', 'chair']
# Slice to end: omit end index (defaults to end of list)
furniture[1:] # Returns all elements from index 1 to end
['chair', 'rack', 'shelf']
furniture[:]
['table', 'chair', 'rack', 'shelf']
Slicing the complete list will perform a copy:
# Slicing creates a copy: [:] creates a shallow copy of the list
spam = ['cat', 'bat', 'rat', 'elephant']
spam2 = spam[:] # Create a copy, not a reference
spam2
['cat', 'bat', 'rat', 'elephant']
spam.append('dog')
spam
['cat', 'bat', 'rat', 'elephant', 'dog']
spam2
['cat', 'bat', 'rat', 'elephant']
Sign in to answer this quiz and track your learning progress
spam[:] create when spam is a list?Getting a list length with len()
# len() returns the number of items in a list
furniture = ['table', 'chair', 'rack', 'shelf']
len(furniture) # Returns 4
4
Changing values with indexes
# Modify list elements by assigning new values to indexes
furniture = ['table', 'chair', 'rack', 'shelf']
furniture[0] = 'desk' # Replace first element
furniture
['desk', 'chair', 'rack', 'shelf']
furniture[2] = furniture[1]
furniture
['desk', 'chair', 'chair', 'shelf']
furniture[-1] = 'bed'
furniture
['desk', 'chair', 'chair', 'bed']
Concatenation and Replication
# List concatenation: combine two lists using + operator
[1, 2, 3] + ['A', 'B', 'C'] # Returns [1, 2, 3, 'A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
# List replication: repeat list multiple times using * operator
['X', 'Y', 'Z'] * 3 # Returns ['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
my_list = [1, 2, 3]
my_list = my_list + ['A', 'B', 'C']
my_list
[1, 2, 3, 'A', 'B', 'C']
Using for loops with Lists
# Iterate over list elements using for loop
furniture = ['table', 'chair', 'rack', 'shelf']
for item in furniture: # Loop through each item
print(item)
table
chair
rack
shelf
Getting the index in a loop with enumerate()
# enumerate() returns both index and value in a loop
furniture = ['table', 'chair', 'rack', 'shelf']
for index, item in enumerate(furniture): # Get index and item together
print(f'index: {index} - item: {item}')
index: 0 - item: table
index: 1 - item: chair
index: 2 - item: rack
index: 3 - item: shelf
Loop in Multiple Lists with zip()
# zip() combines multiple lists element-wise in a loop
furniture = ['table', 'chair', 'rack', 'shelf']
price = [100, 50, 80, 40]
for item, amount in zip(furniture, price): # Pair elements from both lists
print(f'The {item} costs ${amount}')
The table costs $100
The chair costs $50
The rack costs $80
The shelf costs $40
The in and not in operators
# in operator: check if an item exists in a list
'rack' in ['table', 'chair', 'rack', 'shelf'] # Returns True
True
'bed' in ['table', 'chair', 'rack', 'shelf']
False
furniture = ['table', 'chair', 'rack', 'shelf']
'bed' not in furniture
True
'rack' not in furniture
False
The Multiple Assignment Trick
The multiple assignment trick is a shortcut that lets you assign multiple variables with the values in a list in one line of code. So instead of doing this:
furniture = ['table', 'chair', 'rack', 'shelf']
table = furniture[0]
chair = furniture[1]
rack = furniture[2]
shelf = furniture[3]
You could type this line of code:
furniture = ['table', 'chair', 'rack', 'shelf']
table, chair, rack, shelf = furniture
table
'table'
chair
'chair'
rack
'rack'
shelf
'shelf'
The multiple assignment trick can also be used to swap the values in two variables:
a, b = 'table', 'chair'
a, b = b, a
print(a)
chair
print(b)
table
The index Method
The index method allows you to find the index of a value by passing its name:
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.index('chair')
1
Adding Values
append()
append adds an element to the end of a list:
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.append('bed')
furniture
['table', 'chair', 'rack', 'shelf', 'bed']
Sign in to answer this quiz and track your learning progress
append() method do to a list?insert()
insert adds an element to a list at a given position:
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.insert(1, 'bed')
furniture
['table', 'bed', 'chair', 'rack', 'shelf']
Removing Values
del
del removes an item using the index:
furniture = ['table', 'chair', 'rack', 'shelf']
del furniture[2]
furniture
['table', 'chair', 'shelf']
del furniture[2]
furniture
['table', 'chair']
remove()
remove removes an item with using actual value of it:
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.remove('chair')
furniture
['table', 'rack', 'shelf']
Removing repeated items
If the value appears multiple times in the list, only the first instance of the value will be removed.
pop()
By default, pop will remove and return the last item of the list. You can also pass the index of the element as an optional parameter:
animals = ['cat', 'bat', 'rat', 'elephant']
animals.pop()
'elephant'
animals
['cat', 'bat', 'rat']
animals.pop(0)
'cat'
animals
['bat', 'rat']
Sign in to answer this quiz and track your learning progress
pop() do when called on a list?Sorting values with sort()
numbers = [2, 5, 3.14, 1, -7]
numbers.sort()
numbers
[-7, 1, 2, 3.14, 5]
furniture = ['table', 'chair', 'rack', 'shelf']
furniture.sort()
furniture
['chair', 'rack', 'shelf', 'table']
You can also pass True for the reverse keyword argument to have sort() sort the values in reverse order:
furniture.sort(reverse=True)
furniture
['table', 'shelf', 'rack', 'chair']
If you need to sort the values in regular alphabetical order, pass str.lower for the key keyword argument in the sort() method call:
letters = ['a', 'z', 'A', 'Z']
letters.sort(key=str.lower)
letters
['a', 'A', 'z', 'Z']
You can use the built-in function sorted to return a new list:
furniture = ['table', 'chair', 'rack', 'shelf']
sorted(furniture)
['chair', 'rack', 'shelf', 'table']
The Tuple data type
The key difference between tuples and lists is that, while tuples are immutable objects, lists are mutable. This means that tuples cannot be changed while the lists can be modified. Tuples are more memory efficient than the lists.
furniture = ('table', 'chair', 'rack', 'shelf')
furniture[0]
'table'
furniture[1:3]
('chair', 'rack')
len(furniture)
4
The main way that tuples are different from lists is that tuples, like strings, are immutable.
Converting between list() and tuple()
tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
list(('cat', 'dog', 5))
['cat', 'dog', 5]
list('hello')
['h', 'e', 'l', 'l', 'o']
Sign in to answer this quiz and track your learning progress