In Python, append
and extend
are two different methods used to add elements to a list, but they behave differently:
- append:
- The
append
method is used to add a single element to the end of a list. - It takes one argument, which is the element you want to add to the list.
- The element is added as a single item, whether it's a value, a variable, or even another list. It becomes a new element within the original list.
- The
Example using append
:
python
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
my_list.append([5, 6])
print(my_list) # Output: [1, 2, 3, 4, [5, 6]]
In this example, append(4)
adds the integer 4
as a single element to the end of the list, and append([5, 6])
adds the list [5, 6]
as a single element to the end of the list.
- extend:
- The
extend
method is used to add multiple elements to the end of a list. - It takes an iterable (e.g., a list, tuple, or string) as an argument, and it adds each element from the iterable to the end of the list.
- The elements from the iterable are added individually, not as a single unit. They become part of the original list, not nested within it.
- The
Example using extend
:
python
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
my_list.extend("abc")
print(my_list) # Output: [1, 2, 3, 4, 5, 'a', 'b', 'c']
In this example, extend([4, 5])
adds the elements 4
and 5
individually to the end of the list, and extend("abc")
adds the characters 'a'
, 'b'
, and 'c'
individually to the end of the list.
To summarize:
append
adds a single element (which can be a value or another list) as a single unit to the end of the list.extend
adds multiple elements from an iterable (such as a list or string) individually to the end of the list.
The choice between append
and extend
depends on your specific use case and whether you want to add a single item or multiple items to a list.
Comments
Post a Comment