RL Researcher

08. 리스트(List) - 2 - 리스트 인덱싱, 리스트 슬라이싱 본문

AI Basic/Python Programming

08. 리스트(List) - 2 - 리스트 인덱싱, 리스트 슬라이싱

Lass_os 2020. 12. 25. 16:45

1. 리스트 인덱싱(List Indexing)


  • Python에서 리스트 인덱싱은 - (음수 인덱싱) 값도 허용합니다.

  • - 값은 역순으로도 인덱싱됩니다.

s = 'show how to index into sequences'.split()
print(s)
print(s[0])
print(s[5])
print(s[-1])
print(s[-2])
print(s[-6])

========================================================================

<output>
['show', 'how', 'to', 'index', 'into', 'sequences']
'show'
'sequences'
'sequences'
'into'
'show'

2. 리스트 슬라이싱(List Slicing)


  • 리스트 슬라이싱은 리스트를 자르는 것을 말합니다.

  • 사용법은 리스트변수[시작인덱스:종료인덱스:step] 입니다. 종료인덱스의 원소는 포함되지 않고 바로 앞 원소까지만 포함됩니다.

print(s[1:4])

========================================================================

<output>
['how', 'to', 'index']
  • 음수 인덱싱도 슬라이싱에 사용할 수 있습니다.

print(s[1:-1])

========================================================================

<output>
['how', 'to', 'index', 'into']
  • 시작인덱스부터 끝까지 포함시키려면 아래와 같이 입력합니다.

  • 리스트변수[시작인덱스:]

print(s[3:])

========================================================================

<output>
['index', 'into', 'sequences']
  • 반대로 처음부터 특정인덱스까지 가져오기 위해서는 아래와 같이 입력합니다.

  • 리스트변수[:종료인덱스]

print(s[:3])

========================================================================

<output>
['show', 'how', 'to']
  • 모든 값을 복사하여 새로운 List를 만들기 위해서는 아래와 같이 입력합니다.

  • 리스트 변수 [:]

full_slice = s[:]
print(full_slice)

========================================================================

<output>
['show', 'how', 'to', 'index', 'into', 'sequences']
  • 슬라이싱을 통해 새롭게 만든 변수와 값은 같지만, 같은 변수는 아닙니다.

print(full_slice == s)
print(full_slice is s)

========================================================================

<output>
True
False
  • step을 활용하여 리스트를 reverse할 수 있습니다.

s = 'show how to index into sequences'.split()
print(s)
print(s[::-1])

========================================================================

<output>
['show', 'how', 'to', 'index', 'into', 'sequences']
['sequences', 'into', 'index', 'to', 'how', 'show']
Comments