본문 바로가기
프로그래밍 언어/Python 3

[Python] 리스트 내에 element가 있는지 확인

by Physics 2021. 3. 22.
728x90

Python 내에서 간단한 명령어를 통해서 List 내의 원소의 존재 유무를 확인하는 방법은 아래와 같이 2가지 방법이 있다. 
  (1) "in" command를 사용하는 것 
  (2) count() 함수를 사용하는 것 

1. <element> in <list>

1) Syntex: elem in LIST
  - 만약 LIST 내에 elem이 존재한다면, True를 반환한다. 그렇지 않을 경우 False를 반환한다. 
  - 만약 LIST 내에 elem이 없는 것을 확인하고자 한다면, not을 다음과 같이 써준다: elem not in LIST
  - "in"을 사용하는 경우, 굉장히 큰 리스트에서는 다른 방법과 비교할 때, 매우 느리다고 한다 [2] 
2) example:  

LIST = ["Korea", "Japan", "China"]
if "Korea" in LIST:
    print("Korea is in LIST") 

 

2.count() 

<list>.count(<elem>) 함수는 list에 elem이 몇 개 존재하는지 알려준다. 따라서, 리턴값이 0보다 크면 elem이 존재하며, 그렇지 않고 0을 반환하는 경우에는 해당 elem이 존재하지 않는다. 

1) example

>>> LIST = ["Korea", "Japan", "China"]
>>> if LIST.count("USA") > 0:
...    print("USA exists in LIST")
... else: 
...    print("USA doesn't exists in LIST")
USA doesn't exists in list

 

3. <List>.__contains__(<elem>) 

>>> l = [1, 2, 3]
>>> l.__contains__(3)
True

 

Reference:
[1] thispointer.com/python-how-to-check-if-an-item-exists-in-list-search-by-value-or-condition/  
[2] stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exists-in-a-list

728x90

댓글