Carrot
Python

[Python] 리스트, 문자열에서 원소 찾기(index, find 차이)

NaDuck 2023. 1. 24. 10:29

index()

>>> li = [1, 2, 3, 4, 5]  # <리스트>
>>> li.index(2)  
1
>>> li.index(4)
3
>>> str = "12345"  # <문자열>
>>> str.index("2")  
1
>>> str.index("4")  
3
  • 리스트, 문자열, 튜플 자료형에서 사용
  • 해당 원소가 없으면 ValueError 에러 발생
>>> li = [1, 2, 3, 4, 5]
>>> li.index(10)  
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    li.index(10)
ValueError: 10 is not in list

 

  • 탐색 범위를 지정하여 찾을 수 있다.
    • 마찬가지로 해당 원소가 없으면 ValueError 에러 발생
>>> a = "hello"
>>> a.index("o", 1, 5)  # 1~4번 인덱스 내에서 탐색
4
>>> a.index("e", 3)  # 3번 인덱스부터 탐색 <- 에러 발생
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    a.index("e", 3)
ValueError: substring not found
>>> a.index("e", 1)  # 1번 인덱스부터 탐색
1

 


find()

>>> str = "12345"  # <문자열>만 가능!
>>> str.find("3")  
2
>>> str.find("5")  
4
  • 문자열에서만 사용 가능
  • 해당 원소가 없으면 -1을 return 
>>> str = "12345"
>>> str.find("7") 
-1

 

  • 탐색 범위를 지정하여 찾을 수 있다. 
    • 마찬가지로 해당 원소가 없으면 -1을 return
>>> a = "hello"
>>> a.find("o", 1, 4)  # 1~3번 인덱스 내에서 탐색
-1
>>> a.find("o", 1, 5)  # 1~4번 인덱스 내에서 탐색
4
>>> a.find("o", 1)  # 1번 인덱스 이후부터 탐색
4
>>> a.find("e", 3)  # 3번 인덱스 이후부터 탐색
-1

 


에러가 발생하지 않으면서 리스트의 원소를 찾기 위해선

(원소) in (리스트)로 먼저 원소의 존재를 확인한다. 

# if (원소) in (리스트):
#	print("원소 존재")

# if (원소) not in (리스트):
#	print("원소 없음")

>>> li = [1, 2, 3, 4, 5]
>>> if 3 in li:
	print(li.index(3))     
3