Python Collection Methods
Introduction
Python collections are data structures that store multiple items in a single variable.
Understanding collection methods helps you manipulate and access data efficiently.
This tutorial covers common methods for lists, tuples, sets, and dictionaries.
Collections are the backbone of data manipulation in Python.
List Methods
Lists are ordered, mutable collections of items.
Python provides many built-in methods to work with lists.
- append(): Adds an item to the end of the list.
- extend(): Adds elements from another iterable to the end.
- insert(): Inserts an item at a specified position.
- remove(): Removes the first occurrence of a value.
- pop(): Removes and returns an item at a given index.
- clear(): Removes all items from the list.
- index(): Returns the index of the first occurrence of a value.
- count(): Returns the number of occurrences of a value.
- sort(): Sorts the list in place.
- reverse(): Reverses the list in place.
Examples of List Methods
Here are some examples demonstrating common list methods.
Tuple Methods
Tuples are ordered, immutable collections.
Because tuples cannot be changed, they have fewer methods.
- count(): Returns the number of times a value appears.
- index(): Returns the index of the first occurrence of a value.
Set Methods
Sets are unordered collections of unique elements.
They support mathematical set operations and have useful methods.
- add(): Adds an element to the set.
- remove(): Removes an element; raises error if not found.
- discard(): Removes an element if present, no error if absent.
- pop(): Removes and returns an arbitrary element.
- clear(): Removes all elements.
- union(): Returns a new set with elements from both sets.
- intersection(): Returns a new set with common elements.
- difference(): Returns a new set with elements in one set but not the other.
- symmetric_difference(): Returns elements in either set but not both.
Dictionary Methods
Dictionaries store key-value pairs and are unordered until Python 3.7+ where they maintain insertion order.
They provide many methods to access and modify data.
- get(): Returns the value for a key, or a default if key not found.
- keys(): Returns a view of all keys.
- values(): Returns a view of all values.
- items(): Returns a view of key-value pairs.
- pop(): Removes a key and returns its value.
- popitem(): Removes and returns an arbitrary key-value pair.
- update(): Updates dictionary with key-value pairs from another dictionary or iterable.
- clear(): Removes all items.
Examples
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
fruits.remove('banana')
print(fruits) # Output: ['apple', 'cherry', 'date']This example adds 'date' to the list and removes 'banana'.
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # Output: {1, 2, 3, 4, 5}
print(a.intersection(b)) # Output: {3}Demonstrates union and intersection of two sets.
person = {'name': 'Alice', 'age': 25}
age = person.get('age')
person.update({'city': 'New York'})
print(person) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}Shows how to get a value and update a dictionary.
Best Practices
- Use list methods like append() and extend() to add elements efficiently.
- Avoid modifying a list while iterating over it to prevent unexpected behavior.
- Use tuples for fixed collections to ensure immutability.
- Use sets to remove duplicates and perform set operations.
- Use dictionary methods like get() to avoid KeyError exceptions.
- Prefer dictionary views (keys(), values(), items()) for efficient iteration.
Common Mistakes
- Trying to use list methods on tuples, which are immutable.
- Using remove() on a set element that does not exist, causing a KeyError.
- Modifying a dictionary while iterating over it.
- Assuming dictionary order before Python 3.7.
- Using pop() without checking if the list or dictionary is empty.
Hands-on Exercise
Practice List Methods
Create a list of your favorite fruits. Use append(), insert(), and remove() methods to modify the list. Print the final list.
Expected output: A list reflecting the additions and removals you performed.
Hint: Start with a list of at least three fruits.
Set Operations
Create two sets with some overlapping numbers. Use union(), intersection(), and difference() methods and print the results.
Expected output: Correct sets showing union, intersection, and difference.
Hint: Use sets with at least 3 elements each, with some common elements.
Dictionary Manipulation
Create a dictionary with keys as names and values as ages. Use get(), update(), and pop() methods to manipulate the dictionary. Print the dictionary after each operation.
Expected output: Dictionary outputs showing the effects of each method.
Hint: Try to get a key that does not exist using get() with a default value.
Interview Questions
What is the difference between a list and a tuple in Python?
InterviewLists are mutable and can be changed after creation, while tuples are immutable and cannot be modified.
How do you remove duplicates from a list in Python?
InterviewYou can convert the list to a set to remove duplicates, then convert back to a list if needed.
What method would you use to safely get a value from a dictionary without risking a KeyError?
InterviewUse the get() method, which returns None or a specified default if the key is not found.
Summary
Python collections provide versatile ways to store and manipulate data.
Lists are mutable and have many methods for modification.
Tuples are immutable and support limited methods.
Sets are unordered collections useful for unique elements and set operations.
Dictionaries store key-value pairs and have methods for safe access and updates.
Mastering collection methods is essential for effective Python programming.
FAQ
Can I modify a tuple after creation?
No, tuples are immutable and cannot be changed after they are created.
What happens if I use remove() on a list element that does not exist?
Python raises a ValueError if the element is not found in the list.
Are dictionary keys ordered?
Starting with Python 3.7, dictionaries preserve insertion order.
How do I safely remove an element from a set without errors?
Use discard() which removes the element if present and does nothing if absent.
