09-19 11:58
Notice
Recent Posts
Recent Comments
반응형
관리 메뉴

BAN2ARU

[Python] append(), extend(), insert() 비교 본문

Language/Python

[Python] append(), extend(), insert() 비교

밴나루 2022. 4. 22. 17:11

Python에서는 요소를 추가하는 함수로 append(), extend(), insert()가 있는데 각각 어떠한 차이가 있는지 알아보자.

간략하게, 한 줄로 각 함수를 설명하면 다음과 같다.

append()

list.append(x)로 활용하며, list의 끝에 x와 같은 요소를 더해준다.

[기존의 list 마지막 위치에 다른 요소 추가]

extend()

list.extend(iterable)로 활용하며, list의 끝에 iterable의 요소들을 더해준다.

[기존의 list에 다른 list 추가]

insert()

list.extend(i,x)로 활용하며, list의 인데스 i 위치에 x와 같은 요소를 더해준다.

[기존의 list의 지정한 위치에 다른 요소 추가]

 

<코드로 보는 예시>

# append() 예시 : list의 마지막에 값이 추가됨
>> temp_list = [1,2,3,4]
>> temp_list.append(5)
>> temp_list
[1,2,3,4,5]


# 만약, list를 추가하게 된다면 : list 그대로 추가되는 것을 볼 수 있음
>> temp_list = [1,2,3,4]
>> temp_list.append([5,6,7])
>> temp_list
[1,2,3,4,[5,6,7]]

# 만약 list 내부에 추가하고 싶다면 ?? extend()를 활용하자
>> temp_list = [1,2,3,4]
>> add_list = [5, 6, 7]
>> temp_list.extend(add_list)
[1,2,3,4,5,6,7]

# extend()에 요소를 넣게 된다면 다음과 같은 오류 발생
>> temp_list = [1,2,3,4]
>> temp_list.extend(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

# insert() 예시 : list에서 원하는 index에 값 추가
>> temp_list = [1,2,3,4]
>> temp_list.insert(1, 5)
>> temp_list
[1,5,2,3,4]
728x90
Comments