Develop
[Python] extend()로 List 자료형에 List 요소 추가하기
너드나무
2024. 11. 18. 08:33
반응형
LIST.extend()
extend()는 리스트뿐 아니라 튜플, 집합(set) 등 다양한 자료형의 요소를
개별적으로 풀어서 리스트에 순서대로 덧붙이는 기능을 제공합니다.
extend() 특징
- 간결한 코드 작성
- 여러 요소를 추가할 때 for 루프나 append()를 반복적으로 호출할 필요가 없습니다.
- 다양한 자료형에 적용 가능
- 리스트뿐 아니라 튜플, 집합, 문자열 등 다양한 자료형의 요소를 추가할 수 있습니다.
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
# extend()를 사용하여 tropical의 요소를 thislist에 추가
thislist.extend(tropical)
print(thislist)
# ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
extend() vs append() 비교
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
# append() 사용 시
thislist.append(tropical)
print("append 사용 결과:", thislist)
# extend() 사용 시
thislist = ["apple", "banana", "cherry"] # 초기화
thislist.extend(tropical)
print("extend 사용 결과:", thislist)
# append 사용 결과: ['apple', 'banana', 'cherry', ['mango', 'pineapple', 'papaya']]
# extend 사용 결과: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
- append()는 리스트 자체를 마지막 요소로 추가하여 리스트 안에 리스트가 들어가는 형태를 만듭니다.
- extend()는 각 요소를 개별적으로 추가해 리스트가 중첩되지 않으므로 코드의 가독성과 자료 접근성이 향상됩니다.
728x90
반응형