티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Append integer to beginning of list in Python

파이썬에서 리스트의 맨 앞에 정수를 추가하는 방법은 무엇인가요?

 문제 내용 

How do I prepend an integer to the beginning of a list?

파이썬에서 리스트의 맨 앞에 정수를 추가하는 방법은 무엇인가요?
[1, 2, 3]  ⟶  [42, 1, 2, 3]

 

 

 높은 점수를 받은 Solution 

>>> x = 42
>>> xs = [1, 2, 3]
>>> xs.insert(0, x)
>>> xs
[42, 1, 2, 3]

 

How it works:

작동 방식:

 

list.insert(index, value)

Insert an item at a given position. The first argument is the index of the element before which to insert, so xs.insert(0, x) inserts at the front of the list, and xs.insert(len(xs), x) is equivalent to xs.append(x). Negative values are treated as being relative to the end of the list.

주어진 위치에 항목을 삽입합니다. 첫 번째 인자는 삽입할 위치의 이전 요소의 인덱스입니다. 즉, xs.insert(0, x)는 리스트의 맨 앞에 삽입하고, xs.insert(len(xs), x)는 xs.append(x)와 같습니다. 음수 값은 리스트의 끝을 기준으로 상대적으로 처리됩니다.

 

 

 

 가장 최근 달린 Solution 

Alternative:

대안:
>>> from collections import deque

>>> my_list = deque()
>>> my_list.append(1)       # append right
>>> my_list.append(2)       # append right
>>> my_list.append(3)       # append right
>>> my_list.appendleft(100) # append left
>>> my_list

deque([100, 1, 2, 3])

>>> my_list[0]

100

 

[NOTE]:

[참고]:

 

collections.deque is faster than Python pure list in a loop Relevant-Post.

collections.deque는 루프에서 순수한 파이썬 리스트보다 더 빠릅니다. 관련 포스트를 참조하세요.

 

 

 

출처 : https://stackoverflow.com/questions/17911091/append-integer-to-beginning-of-list-in-python

반응형
댓글
공지사항
최근에 올라온 글