파이썬 python list 값 요소 찾기

python list에서 원하는 값(요소)를 찾는 방법에 대해 알아보겠습니다.
list안의 값을 찾는 법은 여러 방법으로 구현할 수 있습니다.
각각의 방법에 대해 비교해보시고 상황에 맞게 적용하시기 바랍니다.

list[index]

list의 값의 index번호를 알고 있으면 index값을 적용하여 값을 가져올 수 있습니다.

list = ['apple', 'melon', 'grape', 'kiwi'] found = list[1] print(found) # print: melon found = list[1] print(found) # print: kiwi

in operator

in 연산자를 이용하여 list에 찾는 값이 존재하는지 확인할 수 있습니다.

list = ['apple', 'melon', 'grape', 'kiwi'] if 'apple' in list: print(True) # print: True list = ['apple', 'melon', 'grape', 'kiwi'] if 'Apple' not in list: print(True) # print: True

NOTE: 찾고자 하는 값이 문자나 문자열일 경우 대소문자를 구분합니다.


list.index

list에서 찾고자 하는 값고 정확히 일치하는 첫번째 값의 index 값을 반환합니다.
존재하는 모든 값의 index를 구하려면 다른 방법으로 구해야합니다.

Syntax: list.index(element)

  • element: list에서 찾고자 하는 값

list = ['apple', 'melon', 'grape', 'kiwi'] found = list.index('melon') print(found) # print: 1 list = ['apple', 'apple', 'melon', 'grape', 'kiwi', 'apple'] found = list.index('apple') print(found) # print: 0 found = list.index('banana') print(found) # print: ValueError: 'banana' is not in list

NOTE: 찾고자 하는 값이 문자나 문자열일 경우 대소문자를 구분합니다.
값이 존재하지 않으면 ValueError를 반환합니다.


list.count

list에서 찾고자 하는 값의 갯수를 반환합니다.
찾고자 하는 값이 존재하지 않으면 0을 반환합니다.

Syntax: list.count(value)

  • value: list에서 찾고자 하는 값
list = ['apple', 'melon', 'grape', 'kiwi'] count = list.count('apple') print(count) # print: 1 list = ['apple', 'apple', 'melon', 'grape', 'kiwi', 'apple'] count = list.count('apple') print(count) # print: 3 count = list.count('banana') print(count) # print: 0 list = ['apple', ['apple', 'melon'], 'grape', 'kiwi', 'apple'] count = list.count(['apple', 'melon']) print(count) # print: 1

INFO: parameter는 string, number, list등의 찾고자 하는 타입을 입력할 수 있습니다.


[Python] - 파이썬 python list to string 리스트를 문자열로 변경

[Python] - 파이썬 python 문자열 찾기

[Python] - 파이썬 python string, array, tuple length 길이

[Python] - 파이썬 python 문자열 공백 제거 / 삭제



+ Recent posts