개발/Python
Enumerate 함수
AimB
2021. 1. 9. 11:56
enumerate는 '열거하다' 라는 뜻이다.
객체에 번호를 매겨 enumerate object로 만들어준다.
for loop에 직접적으로 사용하거나 list() 메소드를 사용하여 리스트 형태로 만들 수 있다.
l1 = ["cat","dog","repeat"] #list
s1 = "cat" #string
# creating enumerate objects
obj1 = enumerate(l1)
obj2 = enumerate(s1)
print ("Return type:",type(obj1))
# Return type: <class 'enumerate'>
print (list(enumerate(l1)))
#[(0, 'cat'), (1, 'dog'), (2, 'repeat')]
print (list(enumerate(s1)))
# [(0, 'c'), (1, 'a'), (2, 't')]]
enumerate는 0부터 번호를 매기는데, 시작 번호를 바꿀 수 있다.
# changing start index to 2 from 0
print (list(enumerate(s1,2)))
# [(2, 'c'), (3, 'a'), (4, 't')]