This chapter introduces lists in Python as mutable ordered sequences of elements that can be of varying data types. It covers list operations, accessing elements, methods, and manipulation techniques like slicing, traversing, and copying lists.
Lists are one of the most versatile data structures in Python, allowing you to store a collection of items in an ordered, mutable format. Unlike strings, which are sequences of characters, lists can hold a mix of data types, including integers, strings, floats, and even other lists. This flexibility makes lists particularly useful for managing groups of related data.
[]) and separated by commas. For example:
list1 = [2, 4, 6, 8, 10, 12] # A list of even numbers
list2 = ['a', 'e', 'i', 'o', 'u'] # A list of vowels
list1[0] # Returns the first element
list1[-1] # Returns the last element
IndexError.list1[3] = 'Black' # Change the fourth element
+): This operator allows you to join two or more lists together.
list3 = list1 + list2 # Combines list1 and list2
*): This operator allows you to repeat a list a specified number of times.
list1 * 3 # Repeats list1 three times
in, not in): These operators check whether an element exists in a list.
'Green' in list1 # Returns True if 'Green' is present
list1[1:4] # Gets elements at index 1 to 3
for loop, allowing you to access each element:
for item in list1:
print(item)
while loop with an index.Several built-in functions help manipulate lists, such as:
len(list): Returns the number of elements in the list.list.append(item): Adds a single element to the end of the list.list.extend(iterable): Appends elements from an iterable to the end of the list.list.insert(index, item): Inserts an element at a specified position.list.remove(item): Removes the first occurrence of a value.list.pop(index): Removes and returns the element at the specified position.list.sort(): Sorts the list in ascending order.nested_list = [[1, 2], [3, 4]]
nested_list[0][1] # Returns 2
Copying a list can be done by simple assignment or several methods that create a shallow copy, ensuring that changes to the copy do not impact the original list:
new_list = old_list[:] # Creates a copy
list() function:
new_list = list(old_list)
copy module. import copy: Allows deep copying as well, which is crucial for nested lists.The chapter concludes with practical examples that illustrate basic list manipulations, including how to append, insert, modify, and delete elements in a list, emphasizing user-driven interactions to perform multiple operations in a single run.