range와 slicing의 문법의 차이를 정리하려 합니다.
1. range
range 함수는 range객체(immutable sequence of numbers)를 반환합니다.
<Python 공식문서의 range설명>
https://docs.python.org/3/library/stdtypes.html#range
1) range(stop) - start는 0으로, step은 1로 고정
2) range(start, stop[, step]) - step은 안주어지면 1로 설정됨
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]
>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18
인덱스 거꾸로 참조할때 range(len(nums)-1,0-1,-1) 또는 reversed(range(len(nums))로 할 수 있습니다.
2. Slicing
slicing은 새로운 리스트 객체를 반환합니다.
음수 index는 그냥 뒤에서부터 세기만 할 뿐 그 위치 자체로 생각!
<slicing에 대한 정리>
https://stackoverflow.com/questions/509211/understanding-slice-notation
a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
a[:] # a copy of the whole array
a=[1,2,3,4,5,6]
a[-1] # 6, last item in the array
a[-2:] # [5,6], last two items in the array
a[:-2] # [1,2,3,4], everything except the last two items
a=[1,2,3,4,5,6]
a[::-1] # [6,5,4,3,2,1], all items in the array, reversed
a[1::-1] # [2,1], the first two items, reversed
a[:-3:-1] # [6,5], the last two items, reversed(step음수일때 start비우면 -1로)
a[-3::-1] # [4,3,2,1], everything except the last two items, reversed
1) step이 양수일때: start없으면 0으로, end없으면 len(리스트)으로
2) step이 음수일때: start없으면 -1으로, end없으면 맨 앞까지(default값 0이나 -1아님)
test_list=[1,2,3,4]
print(test_list[-1::-1]) #[4,3,2,1]
print(test_list[-1:0:-1]) #[4,3,2]
print(test_list[-1:-1:-1]) #[]
'Python > for코테' 카테고리의 다른 글
[이것이 코딩 테스트다 with Python] 13강 그리디 알고리즘 유형 문제 풀이 (0) | 2021.01.15 |
---|---|
[이것이 코딩 테스트다 with Python] 12강 그리디 알고리즘 개요 (0) | 2021.01.15 |
[이것이 코딩 테스트다 with Python] 11강 파이썬 문법: 자주 사용되는 표준 라이브러리 (0) | 2021.01.13 |
[이것이 코딩 테스트다 with Python] 10강 파이썬 문법: 함수와 람다 표현식 (0) | 2021.01.13 |
[이것이 코딩 테스트다 with Python] 9강 파이썬 문법: 반복문 (0) | 2021.01.13 |