In Python, a list is a collection of items that are stored in a specific order. It's a versatile data type because it can store any type of data, such as numbers, strings, or even other lists. Lists are mutable, meaning you can change their content after they are created.
Key Characteristics of Lists:
# Creating a list my_list = [1, 2, 3, 'apple', 'banana'] # Accessing elements print(my_list[0]) # Output: 1 # Slicing print(my_list[2:4]) # Output: [3, 'apple'] # Modifying elements my_list[3] = 'orange' print(my_list) # Output: [1, 2, 3, 'orange', 'banana'] # Adding elements my_list.append('grape') print(my_list) # Output: [1, 2, 3, 'orange', 'banana', 'grape'] # Removing elements my_list.remove(2) print(my_list) # Output: [1, 3, 'orange', 'banana', 'grape']
Python provides several built-in functions that can be used with lists:
len()
: Returns the number of elements in a list.append()
: Adds an element to the end of the list.insert()
: Inserts an element at a specified position.remove()
: Removes the first occurrence of a specified element.pop()
: Removes and returns the element at the specified position.index()
: Returns the index of the first occurrence of a specified value.count()
: Returns the number of occurrences of a specified element.sort()
: Sorts the list.reverse()
: Reverses the order of the list.# Using built-in functions with lists numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5] # len() length = len(numbers) print("Length of the list:", length) # Output: Length of the list: 9 # Adding an element numbers.append(7) print(numbers) # Output: [3, 1, 4, 1, 5, 9, 2, 6, 5, 7] # insert element 10 at 2nd position numbers.insert(2, 10) print(numbers) # Output: [3, 1, 10, 4, 1, 5, 9, 2, 6, 5, 7] # Removing an element numbers.remove(5) print(numbers) # Output: [3, 1, 10, 4, 1, 9, 2, 6, 5, 7] # Removing element at 2nd position popped = numbers.pop(2) print("Popped element:", popped) # Output: Popped element: 10 print("Updated list:", numbers) # Output: Updated list: [3, 1, 4, 1, 9, 2, 6, 5, 7] # Returns the index of the first occurrence of a value 1 index = numbers.index(1) print("Index of first occurrence of 1:", index) # Output: Index of first occurrence of 1: 1 # Returns the number of occurrences of a 1 count = numbers.count(1) print("Number of occurrences of 1:", count) # Output: Number of occurrences of 1: 2 # Sorting numbers.sort() print(numbers) # Output: [1, 1, 2, 3, 4, 5, 6, 7, 9] # Reverse numbers.reverse() print("Reversed list:", numbers) # Output: Reversed list: [9, 7, 6, 5, 4, 3, 2, 1, 1]