Python List index / 요소 찾기 / 갯수 찾기 ( index, in, count )

1. List.index(element)

List 내에서 element의 번호(index)를  리턴합니다. 없는 경우 ValueError

 

>>> list = ['사과', '바나나', '오렌지', '포도']
>>> list.index('포도')
3
>>> list.index('사과')
0
>>> list.index('망고')
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    ValueError: '망고' is not in list

 

다른 프로그래밍 언어에서는 없는요소의 index를 찾을 경우 -1을 리턴하는 경우가 있지만 Python에서는 ValueError를 리턴한다는 사실을 인지하여 헷갈리지 말아야겠습니다.

 

2. element in List

List 내에 element 가 있는지 여부를 리턴합니다. ( True / False )

 

>>> 12 in [12,25,32,47]
True
>>> 14 in [12,25,32,47]
False
>>> 25 not in [12,25,32,47]
False
>>> 17 not in [12,25,32,47]
True

not in 은 말그대로 없는지 여부를 리턴합니다. ( True / False )

 

3. List.count(element)

List 내에 element의 개수를 리턴합니다.

 

>>> list = [1,3,4,9,13,17,1,3,5,4]
>>> list.count(3)
2
>>> list.count(13)
1
>>> list.count(15)
0