[Python] range and enumerate

2023. 6. 7. 16:28·Programming
728x90
728x90

range 란

엄밀하게 애기하면, range 는
숫자들의 immutable sequence 를 생성하기 위한
Lazy Iterable (메모리 효율적인)

을 나타내는 built-in type이다.

 

 

즉, 흔히 built-in function으로 애기하는 range() 는 사실은 range class의 instance를 생성하는 생성자에 해당한다.

 

sequence는 index를 통해 접근 가능한,
즉 item들이 놓여있는 순서가 의미를 가지는 자료구조를 추상화한 것이다.

 

https://dsaint31.tistory.com/569#Sequence

 

[Math] Sequence (수열) and Series (급수)

Sequence수열, 열 이라고 불림.numbers나 objects 들이 순서를 가지고(ordered) 나열된 것을 가리킴.order(순서)가 의미를 가지며, (order가 다르기 때문에 )중복이 허용이 된다.대표적인 예로 arithmetic sequence(

dsaint31.tistory.com

 

0에서 19까지 1씩 증가하는 list 를 만드는 방법에서

range와 list생성자를 다음과 같이 사용한다.

a = list(range(0,20,1)) # list(range(20))

 

range의 생성자에서 paramerter들은 다음과 같음.

  • 첫번째 parameter는 start로 sequence의 첫번째 item에 해당하는 숫자임.
  • 두번째 parameter는 stop으로 해당 숫자보다 하나 적은 숫자가 sequence의 마지막 item이 된다.
    (negative step의 경우엔 하나 큰 숫자가 마지막 item이 됨. 즉, exclusive임)
  • 세번째 parameter는 step으로 sequence에서 인접한 item들 간의 차이가 얼마나 되는지를 나타낸다.

흔히 argument를 하나만 줄 경우, start=0, step=1로 기본 할당되고, 주어진 argument는 stop으로 동작한다.
argument가 두 개 주어질 경우, step=1로 기본 할당되고 나머지 parameter들은 순서대로 argument를 값으로 가진다.

 

참고로 range의 arguments들은 sequence type의 객체들의 slicing과 매우 유사하다.

  • -1이 sequence type의 위치를 나타내는 데 사용되는 경우, 맨 마지막 위치를 가르킴.
  • -1이 step으로 사용될 경우, 역순으로 iterate가 이루어짐.

range의 생성자는 integer만을 argument로 받는다.


for loop 와의 활용.

10회 반복이나 7회 반복 등이 요구되는 반복문을 만들 때, forloop와 range는 자주 같이 사용된다.

  • for statement는 iterable 객체의 item들을 iterate하는 loop structure임.
  • range는 for statement에서 많이 사용되는 "숫자들로 구성된 iterable 객체"를 효과적으로 제공해준다.
  • range는 class로 일종의 generator처럼 동작함.

 

0~9까지의 수행을 원한다면 다음과 같이 구성된다.

for i in range(10):
    print(i)
    # 반복될 코드 블럭

1부터 수행한다면 range(1,11)을 사용하여 1~10까지 수행되도록 할 수 있다.

 

참고로 programming에서는 sequence등에 접근할 때 index를 0부터 사용하는 것이 관례 (zero-based numbering)이다.

Matlab 등의 특이한 경우를 제외하고는 0부터 counting을 하기 때문에 여기에 익숙해지는 것이 좋다.


enumerate 사용하기

forloop에서 현재 iteration 횟수(또는 현재 item의 index)를 명시적으로 확인해야하는 경우에

사용되는 함수(built-in function)이다.

 

Python의 enumerate 함수는 
반복 가능한(iterable) 객체를 입력받아, 
각 item(요소)를 순회하면서
index와 함께 item를 묶은 tuple을 반환하는
enumerater 객체를 생성

 

enumerate함수는 enumerater object를 반환해주면서 

각 반복에서 argument로 넘겨준 iterable의 item과 함께

해당 item의 index에 해당하는 int의 숫자를 반환해준다.

(index와 argument를 묶은 tuple를 __next__()호출마다 반환한다.)

a = ['one', 'two', 'three', 'four'] # list is an iterable object.

for t in enumerate(a):
    idx = t[0]
    item = t[1]
    print(f'iteration {idx}: {item}')

# 다음 코드 형태로 더 많이 이용됨.
# for idx,item in enumerate(a):    
#     print(f'iteration {idx}: {item}')

 

참고로 enumerate(a, 8)이라고 바꾸면, index가 8부터 시작한다.

 

index만 필요한 경우엔 다음과 같은 방법을 추천한다.

for idx, _ in enumerate(iterator):
	do_something(idx)
    
# 아래도 같은 동작이지만, Pythonic way가 아님: 비추천
for idx in range(len(iterator)):
	do_something(idx)

References

https://docs.python.org/3.6/library/stdtypes.html#ranges

 

4. Built-in Types — Python 3.6.15 documentation

The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some collection classes are mutable. The methods that add, subtract,

docs.python.org

https://docs.python.org/3.6/library/functions.html?highlight=enumerate#enumerate

 

2. Built-in Functions — Python 3.6.15 documentation

2. Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs(x) Return the absolute value of a number. The argument may be an integer or a floating

docs.python.org

https://gist.github.com/dsaint31x/5bbd005845eeb7a92e2537cf5036769e

 

py_range_enumerate.ipynb

py_range_enumerate.ipynb. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

https://ds31x.tistory.com/229

 

[Python] Enum (열거형, Enumeration Type)

Enum은 Enumeration type의 abbreviation. 한정된 수의 가능한 값을 value로 가질 수 있는 데이터 타입 을 가르킴.(보통 프로그래머가 가질 수 있는 값들의 집합을 정의해줌.) 프로그래밍에서 Enum을 사용하면

ds31x.tistory.com


 

728x90

'Programming' 카테고리의 다른 글

[Python] Python Script File 실행해보기  (0) 2023.06.09
[Programming] Application Programming Interface (API)  (1) 2023.06.08
[Python] Iterable and Iterator, plus Generator  (1) 2023.06.07
[Python] Comprehension (list, dict, set) and Generator Expression  (0) 2023.06.06
[Python] Assignment와 Shallow Copy, Deep Copy  (0) 2023.06.05
'Programming' 카테고리의 다른 글
  • [Python] Python Script File 실행해보기
  • [Programming] Application Programming Interface (API)
  • [Python] Iterable and Iterator, plus Generator
  • [Python] Comprehension (list, dict, set) and Generator Expression
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (787)
      • Private Life (15)
      • Programming (206)
        • DIP (116)
        • ML (35)
      • Computer (120)
        • CE (54)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (368)
        • Signals and Systems (115)
        • Math (176)
        • Linear Algebra (33)
        • Physics (43)
        • 인성세미나 (1)
      • 정리필요. (61)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (7)
        • PET Study 2009 (1)
        • 방사선 장해방호 (5)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    opencv
    signals_and_systems
    math
    SIGNAL
    Python
    signal_and_system
    random
    인허가제도
    Optimization
    linear algebra
    SS
    Probability
    numpy
    cv2
    Programming
    function
    fourier transform
    ML
    Vector
    Term
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] range and enumerate
상단으로

티스토리툴바