complete list of list methods in python
1. Adding Elements
append()extend()insert()
2. Removing Elements
remove()pop()clear()
3. Accessing Elements
index()count()
4. Sorting & Reversing
sort()reverse()
5. Copying & Joining
copy()
6. List Comparison & Operations
- (No direct methods, but
==,+,*are used with lists)
Note:
- These are the built-in methods for lists in Python (as of Python 3.x).
- Some operations (like slicing, concatenation) use syntax rather than methods.
Python List copy() Method with Examples
The copy() method in Python returns a shallow copy of a list. This means it creates a new list with the same elements as the original, but the new list is a separate object in memory.
Key Points:
- Creates a new list with the same elements
- Modifications to the new list won’t affect the original
- Shallow copy means nested objects are still references to the same objects
Examples:
Example 1: Basic copy
python
original = [1, 2, 3] copied = original.copy() print(copied) # Output: [1, 2, 3] print(original is copied) # Output: False (they are different objects)
Example 2: Modifying the copy doesn’t affect original
python
fruits = ['apple', 'banana', 'cherry']
fruit_copy = fruits.copy()
fruit_copy.append('orange')
print(fruits) # Output: ['apple', 'banana', 'cherry']
print(fruit_copy) # Output: ['apple', 'banana', 'cherry', 'orange']
Example 3: Shallow copy demonstration (nested lists)
python
original = [[1, 2], [3, 4]] copied = original.copy() copied[0][0] = 99 print(original) # Output: [[99, 2], [3, 4]] (nested list is shared)
Example 4: Copy vs assignment
python
a = [1, 2, 3] b = a # assignment (same object) c = a.copy() # copy (new object) a.append(4) print(b) # Output: [1, 2, 3, 4] (b is same as a) print(c) # Output: [1, 2, 3] (c is independent)
Example 5: Copying empty list
python
empty = [] empty_copy = empty.copy() empty_copy.append(1) print(empty) # Output: [] print(empty_copy) # Output: [1]
For deep copies (where nested objects are also copied), you would use the copy.deepcopy() function from the copy module instead.