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

숭글·2023년 1월 30일
0

array에 새로운 element를 추가하는 함수이다.

array.append(x)
array.extend(x:iterable)
array.insert(idx, x)

append(x)
Append a new item with value x to the end of the array.

extend(iterable)
Append items from iterable to the end of the array.

  • If iterable is another array
    :it must have exactly the same type code; if not, TypeError will be raised.
  • If iterable is not an array
    : it must be iterable and its elements must be the right type to be appended to the array.

insert(i, x)
Insert a new item with value x in the array before position i. Negative values are treated as being relative to the end of the array.

Example

append()

arr = [1, 2, 3]
tempArr = [4, 5]

arr.append(tempArr)
print(arr)

output >

[1, 2, 3, [4, 5]]

append(x)는 추가하는 요소 그 자체를 추가한다.

extend()

arr = [1, 2, 3]
tempArr = [4, 5]

arr.extend(tempArr) 
print(arr)

output >

[1, 2, 3, 4, 5]

extend(iterable)는 iterable의 요소를 차례로 하나씩 추가한다.

insert()

arr = [1, 2, 3]
arr2 = [1, 2, 3]
arr3 = [1, 2, 3]
tempArr = [4, 5]

arr.insert(0, tempArr)
arr2.insert(2, tempArr)
arr3.insert(len(arr3), tempArr)
print(arr)
print(arr2)
print(arr3)

output >

[[4, 5], 1, 2, 3]
[1, 2, [4, 5], 3]
[1, 2, 3, [4, 5]]

insert(i, x)는 i의 전에 x를 추가한다.


📖 docs

profile
Hi!😁 I'm Soongle. Welcome to my Velog!!!

0개의 댓글