Programming Languages/Python

python enumerate 의 사용

minjiwoo 2022. 1. 17. 18:11
728x90

 

enumerate(iterable한 객체, start=0) 

enumerate는 파이썬 내장함수로, 반복문에서 사용되어 인덱스iterable한 객체의 데이터가 묶인 튜플을 반환한다. 

여기서 iterable의 의미:  member를 하나씩 차례로 반환 가능한 object를 말한다. iterable한 데이터 타입의 예로는, list, str, tuple이 있다.

enumerate 의 파라미터는 iterable한 원소와 index이다. index는 생략가능하며, 지정해주지 않을 경우에 0부터 시작한다.

다음과 같이 for문의 인자를 하나만 설정해주면, 결과값으로 튜플이 반환된다. 

data = ['A', 'B', 'C'] # iterable한 list

for i in enumerate(data):
    print(i)

다음은 코딩테스트에서 가끔 유용했던 사용 방법이다. index와 해당 순서의 데이터 값을 각각 사용할 수 있다. 

for index, data in enumerate(data):
    print(index, data)

 

또한 enumerate 의 두번째 parameter 인 start에 값을 설정해주어서, 시작 인덱스를 활용할 수 있다. 

for index, data in enumerate(data, start=100):
    print(index, data)
    
#실행결과 --------------------
#100 A
#101 B
#102 C

 

 

 

<참고자료>

https://www.geeksforgeeks.org/enumerate-in-python/

 

Enumerate() in Python - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

728x90