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]
'Python > TIL' 카테고리의 다른 글
[TIL] 220924 enumerate, zip 함수, 리스트 컴프리헨션, 딕셔너리 컴프리헨션 (0) | 2022.09.24 |
---|