Python
[Python] append() vs. extend() 공통점과 차이점
Se On
2024. 8. 17. 21:54
한 눈에 보기
공통점
- append(), extend() 모두 목록의 끝에 무언가를 추가하는 메서드입니다.
차이점
- a list에 b list를 추가하고 싶을 때 어떤 메서드를 사용하느냐에 따라 결과는 상이합니다.
- append: ['apple', 'banana', 'cherry', ["Ford", "BMW", "Volvo"]]
- extend: ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
append()
- The append() method appends an element to the end of the list.
목록의 끝에 요소를 추가합니다. - list.append(elmnt)
Parameter | Description |
elmnt | Required. An element of any type (string, number, object etc.) |
a = ["apple", "banana", "cherry"]
b = ["Ford", "BMW", "Volvo"]
a.append(b)
print(a)
# ['apple', 'banana', 'cherry', ["Ford", "BMW", "Volvo"]]
extend()
- The extend() method adds the specified list elements (or any iterable) to the end of the current list.
목록의 끝에 지정된 반복 가능한 목록 요소를 추가합니다. - list.extend(iterable)
Parameter | Description |
iterable | Required. Any iterable (list, set, tuple, etc.) |
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
# ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
참고자료
- https://www.shiksha.com/online-courses/articles/difference-between-append-and-extend-in-python/
- https://www.w3schools.com/python/ref_list_append.asp
- https://www.w3schools.com/python/ref_list_extend.asp
반응형