Let's Run Jinyeah

[Python] List - Negative Slicing 본문

Programming/Python

[Python] List - Negative Slicing

jinyeah 2021. 1. 25. 15:16

List slicing notation


a[start_index : stop_index]

a[start_index : stop_index : step_size]


  • 리스트의 가장 처음부터 or 마지막까지를 슬라이싱할 경우 start_index 또는 stop_index 생략 가능
  • 슬라이싱 결과는 (stop_index-1)번째 원소까지 포함 (stop_index의 item은 제외)

List slicing with negative index and negative step value


# negative start or stop index
a[-1] # 마지막 item
a[-2:] # 마지막에서 두번째 item부터 마지막 item까지
a[:-2] # 처음부터 마지막에서 두번째 item 전까지

# negative step size
a[::-1] # 마지막 item을 시작으로 처음 item까지(reversed)
a[1::-1] # 앞에서 두번째 item과 첫번째 item

# negative start or stop index with negatvie step_size
a[:-3:-1] # 마지막 item과 마지막에서 두번째 item
a[-3::-1] # 마지막에서 세번째 item부터 처음 item까지

 

step_size가 음수일 경우 슬라이싱의 첫번째의 아이템은 리스트의 마지막 아이템이 된다. 즉, start_index가 생략된 경우(ex. a[:-3:-1]), 마지막부터 슬라이싱이 시작된다. 따라서 슬라이싱 결과는 start_index부터 reversed된 리스트이다.

 

Comments