티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How do I get the last element of a list?
리스트의 마지막 아이템을 가져오는 가장 효과적인 방법
문제 내용
How do I get the last element of a list?
리스트의 마지막 요소를 가져오려면 어떻게 해야 합니까?
Which way is preferred?
어떤 방법이 선호되나요?
alist[-1]
alist[len(alist) - 1]
높은 점수를 받은 Solution
some_list[-1]
is the shortest and most Pythonic.
some_list[-1]는 가장 짧고 가장 파이썬스럽다.
In fact, you can do much more with this syntax. The some_list[-n]
syntax gets the nth-to-last element. So some_list[-1]
gets the last element, some_list[-2]
gets the second to last, etc, all the way down to some_list[-len(some_list)]
, which gives you the first element.
실제로 이 구문을 사용하면 훨씬 더 많은 작업을 수행할 수 있습니다. some_list[-n] 구문은 n번째에서 마지막 요소를 가져옵니다. 그래서 some_list[-1]는 마지막 요소를 얻고, some_list[-2]는 마지막에서 두번째 요소를 얻고, some_list[-len(some_list))는 첫 번째 요소를 제공하는 some_list[-len(some_list))까지 내려간다.
You can also set list elements in this way. For instance:
이러한 방법으로 리스트 요소를 설정할 수도 있습니다. 예를 들어:
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
Note that getting a list item by index will raise an IndexError
if the expected item doesn't exist. This means that some_list[-1]
will raise an exception if some_list
is empty, because an empty list can't have a last element.
인덱스별로 목록 항목을 가져오면 예상 항목이 없는 경우 IndexError가 발생합니다. 이것은 빈 목록은 마지막 요소를 가질 수 없기 때문에 일부_list[-1]가 비어 있으면 예외가 발생한다는 것을 의미합니다.
가장 최근 달린 Solution
METHOD 1:
방법 1:
L = [8, 23, 45, 12, 78]
print(L[len(L)-1])
METHOD 2:
방법 2:.
L = [8, 23, 45, 12, 78]
print(L[-1])
METHOD 3:
방법 3:
L = [8, 23, 45, 12, 78]
L.reverse()
print(L[0])
METHOD 4:
방법 4:
L = [8, 23, 45, 12, 78]
print(L[~0])
METHOD 5:
방법 5:
L = [8, 23, 45, 12, 78]
print(L.pop())
All are outputting 78
모두 78개를 출력하고 있다.
출처 : https://stackoverflow.com/questions/930397/how-do-i-get-the-last-element-of-a-list
'개발 > 파이썬' 카테고리의 다른 글
가장 효율적인 변수 타입 확인 방법 (0) | 2022.12.02 |
---|---|
값 기준으로 Dictionary 정렬하기 (0) | 2022.12.02 |
리스트를 같은 크기의 청크로 분할하기 (0) | 2022.12.02 |
Python List의 append()와 extend()의 차이점 (0) | 2022.12.02 |
Pandas 데이터 프레임에서 열 삭제하기 (0) | 2022.12.01 |