Lists in Python
Lists in Python
Lists are a basic sequential data type that store values in an ordered array.
Lists are mutable objects, meaning they can be altered after creation.
New objects can be added.
Objects can be removed without creating a new list in memory.
Lists are heterogeneous objects, allowing values of different types (integers, strings, floats, booleans, etc.) within the same list.
Constructing a List
To create a list, put a sequence of objects separated by commas within square brackets:
Example:
my_list = ["lesson", 5, "is fun?", True] print(my_list)
Alternatively, use the
list()function to construct a list:This function iterates through a string, making each letter a separate entry in the list.
second_list = list("life is study") print(second_list) # Output: ['l', 'i', 'f', 'e', ' ', 'i', 's', ' ', 's', 't', 'u', 'd', 'y']
Empty List: create a list with no entries using empty square brackets.
Example:
empty_list = [] print(empty_list) # Output: []
Adding and Removing Objects
Adding Objects: use
.append()to add new objects to an existing list.Example:
empty_list.append("I'm no longer empty") print(empty_list)
Removing Objects: use
.remove()to delete a specific object from a list..remove()deletes the first matching item only.my_list.remove(5)
Joining Lists: Use the
+operator to combine two lists.Example:
combined_list = my_list + empty_list print(combined_list)
Extending Lists: Use
.extend()to add a sequence to the end of an existing list.my_list.extend(empty_list)
List Functions
len(): Check the length of a list.Example:
num_list = [1, 2, 3, 4, 5] print(len(num_list)) # Output: 5
max(): Check the maximum value of a list.min(): Check the minimum value of a list.sum(): Calculate the sum of all values in a list.Mean Calculation: The mean can be easily found by dividing the sum of a list by its length.
Checking Membership: Use the
inkeyword to check if a value exists in a list.Example:
print(1 in num_list) # Output: True print(6 in num_list) # Output: False
not in: Check if a list does not contain a certain object..count(): Count occurrences of a given object within a list.Example:
print(num_list.count(3)) # Output: 1
.sort(): Sort the elements of the list..reverse(): Reverse the order of elements in the list.Note: The methods
.reverse()and.sort()mutate the list directly.reversed()andsorted(): These functions return a reversed/sorted version of the list, but do not alter the original list.
List Indexing and Slicing
Indexing: Accessing elements within a list using their index.
Indexes start at 0.
For a list of length , the final index is .
another_list = ["hello", "my", "bestest", "friend", 123] print(another_list[0]) # Output: hello print(another_list[2]) # Output: bestest
Negative Indexing: Access items from the end of the list using negative indices.
-1refers to the last item,-2refers to the second-to-last item, and so on.print(another_list[-1]) # Output: 123 print(another_list[-3]) # Output: bestest
IndexError: Occurs if you supply an index that is beyond the length of the list.
Multiple Indexing: If a list contains indexable objects, multiple indexing operations can be performed.
Nested Lists: Lists containing other lists.
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(nested_list[0][2]) # Output: 3
Slicing: Getting multiple items from a list using a range of values.
list[start:end]gets all objects from indexstarttoend, excluding the item at indexend.print(another_list[1:3]) # Output: ['my', 'bestest']Step Size:
list[start:end:step]specifies a step size.print(another_list[0:6:2]) # Output: ['hello', 'bestest', 123]Slicing up to a certain index:
list[:end]gets everything up to indexend.print(another_list[:4]) # Output: ['hello', 'my', 'bestest', 'friend']Slicing from a given index to the end:
list[start:]gets everything from indexstartto the end.print(another_list[2:]) # Output: ['bestest', 'friend', 123]Negative Step: Slicing from the end toward the beginning.
print(another_list[4:2:-1]) # Output: [123, 'friend']Slicing the entire list:
list[:]creates a copy of the entire list.Reversing a list using slicing:
list[::-1]
Modifying Lists with Indexing
Assigning new values: Use indexing to assign new values to a list at a given position.
Example:
another_list[3] = "new" print(another_list) # Output: ['hello', 'my', 'bestest', 'new', 123]
Deleting items: Use the
delfunction to delete an item at a specific index.Example:
del another_list[3] print(another_list) # Output: ['hello', 'my', 'bestest', 123]
.pop(): Remove and return the final item from a list.Example:
next_item = another_list.pop() print(next_item) # Output: 123 print(another_list) # Output: ['hello', 'my', 'bestest']
List Resizing: Lists resize dynamically as items are added or deleted.
Performance Notes:
Appending and popping from the end of a list are fast operations.
Inserting or deleting items within the body of a list can be slower due to shifting elements in memory.
Copying Lists
Mutable Objects: Lists can be changed in place without creating a completely new list.
Copying Lists: Creates a whole new list in memory.
.copy(): Create a copy of a list.Example:
list1 = [1, 2, 3] list2 = list1.copy() list1.append(4) print(list1) # Output: [1, 2, 3, 4] print(list2) # Output: [1, 2, 3]
Shallow Copy: The
.copy()function performs a shallow copy.It only copies the base level of the list. If there are nested objects, it doesn't copy the nested aspects.
Deep Copy: Creates a copy of everything, including nested objects.
Use the
copymodule for deep copies:import copy list1 = [1, 2, 3] list2 = ["string", list1] list3 = copy.deepcopy(list2) list1.append(4) print(list2) # Output: ['string', [1, 2, 3, 4]] print(list3) # Output: ['string', [1, 2, 3]]
Lists are a very common and ubiquitous data structure in Python.
For data analysis and data science, other sequential data structures are available that allow for faster mathematical operations.
Next Lesson: Tuples and Strings