Python/TIL

[TIL] Append vs Extend in python

kyra 2024. 4. 23. 11:05
Append
  • The append() method adds a single element to the end of a list.
  • If the element being added is a sequence (list, tuple, etc.), it will add that entire sequence as a single element to the list.
fruits = ['apple', 'banana']
fruits.append('orange')
print(fruits)  # ['apple', 'banana', 'orange']

nested_list = [1, 2]
fruits.append(nested_list)
print(fruits)  # ['apple', 'banana', 'orange', [1, 2]]

 

 

Extend
  • The extend() method adds all the elements of an iterable (sequence) to the end of a list.
  • If the iterable being added is a list, it will add each element of that list individually to the original list.
fruits = ['apple', 'banana']
fruits.extend(['orange', 'grape'])
print(fruits)  # ['apple', 'banana', 'orange', 'grape']

nested_list = [1, 2]
fruits.extend(nested_list)
print(fruits)  # ['apple', 'banana', 'orange', 'grape', 1, 2]