Here’s the Pythonic way to do it:
data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
any(e[1] == search for e in data)
Or… well, I’m not going to claim this is the “one true Pythonic way” to do it because at some point it becomes a little subjective what is Pythonic and what isn’t, or which method is more Pythonic than another. But using any()
is definitely more typical Python style than a for
loop as in e.g. RichieHindle’s answer,
Of course there is a hidden loop in the implementation of any
, although it breaks out of the loop as soon as it finds a match.
Since I was bored I made a timing script to compare performance of the different suggestions, modifying some of them as necessary to make the API the same. Now, we should bear in mind that fastest is not always best, and being fast is definitely not the same thing as being Pythonic. That being said, the results are… strange. Apparently for
loops are very fast, which is not what I expected, so I’d take these with a grain of salt without understanding why they’ve come out the way they do.
Anyway, when I used the list defined in the question with three sublists of two elements each, from fastest to slowest I get these results:
- RichieHindle’s answer with the
for
loop, clocking in at 0.22 μs - Terence Honles’ first suggestion which creates a list, at 0.36 μs
- Pierre-Luc Bedard’s answer (last code block), at 0.43 μs
- Essentially tied between Markus’s answer and the
for
loop from the original question, at 0.48 μs - Coady’s answer using
operator.itemgetter()
, at 0.53 μs - Close enough to count as a tie between Alex Martelli’s answer with
ifilter()
and Anon’s answer, at 0.67 μs (Alex’s is consistently about half a microsecond faster) - Another close-enough tie between jojo’s answer, mine, Brandon E Taylor’s (which is identical to mine), and Terence Honles’ second suggestion using
any()
, all coming in at 0.81-0.82 μs - And then user27221’s answer using nested list comprehensions, at 0.95 μs
Obviously the actual timings are not meaningful on anyone else’s hardware, but the differences between them should give some idea of how close the different methods are.
When I use a longer list, things change a bit. I started with the list in the question, with three sublists, and appended another 197 sublists, for a total of 200 sublists each of length two. Using this longer list, here are the results:
- RichieHindle’s answer, at the same 0.22 μs as with the shorter list
- Coady’s answer using
operator.itemgetter()
, again at 0.53 μs - Terence Honles’ first suggestion which creates a list, at 0.36 μs
- Another virtual tie between Alex Martelli’s answer with
ifilter()
and Anon’s answer, at 0.67 μs - Again a close-enough tie between my answer, Brandon E Taylor’s identical method, and Terence Honles’ second suggestion using
any()
, all coming in at 0.81-0.82 μs
Those are the ones that keep their original timing when the list is extended. The rest, which don’t, are
- The
for
loop from the original question, at 1.24 μs - Terence Honles’ first suggestion which creates a list, at 7.49 μs
- Pierre-Luc Bedard’s answer (last code block), at 8.12 μs
- Markus’s answer, at 10.27 μs
- jojo’s answer, at 19.87 μs
- And finally user27221’s answer using nested list comprehensions, at 60.59 μs
На чтение 4 мин Просмотров 5.2к. Опубликовано 03.03.2023
Содержание
- Введение
- Поиск методом count
- Поиск при помощи цикла for
- Поиск с использованием оператора in
- В одну строку
- Поиск с помощью лямбда функции
- Поиск с помощью функции any()
- Заключение
Введение
В ходе статьи рассмотрим 5 способов поиска элемента в списке Python.
Поиск методом count
Метод count() возвращает вхождение указанного элемента в последовательность. Создадим список разных цветов, чтобы в нём производить поиск:
colors = ['black', 'yellow', 'grey', 'brown']
Зададим условие, что если в списке colors присутствует элемент ‘yellow’, то в консоль будет выведено сообщение, что элемент присутствует. Если же условие не сработало, то сработает else, и будет выведена надпись, что элемента отсутствует в списке:
colors = ['black', 'yellow', 'grey', 'brown']
if colors.count('yellow'):
print('Элемент присутствует в списке!')
else:
print('Элемент отсутствует в списке!')
# Вывод: Элемент присутствует в списке!
Поиск при помощи цикла for
Создадим цикл, в котором будем перебирать элементы из списка colors. Внутри цикла зададим условие, что если во время итерации color приняла значение ‘yellow’, то элемент присутствует:
colors = ['black', 'yellow', 'grey', 'brown']
for color in colors:
if color == 'yellow':
print('Элемент присутствует в списке!')
# Вывод: Элемент присутствует в списке!
Поиск с использованием оператора in
Оператор in предназначен для проверки наличия элемента в последовательности, и возвращает либо True, либо False.
Зададим условие, в котором если ‘yellow’ присутствует в списке, то выводится соответствующее сообщение:
colors = ['black', 'yellow', 'grey', 'brown']
if 'yellow' in colors:
print('Элемент присутствует в списке!')
else:
print('Элемент отсутствует в списке!')
# Вывод: Элемент присутствует в списке!
В одну строку
Также можно найти элемент в списке при помощи оператора in всего в одну строку:
colors = ['black', 'yellow', 'grey', 'brown']
print('Элемент присутствует в списке!') if 'yellow' in colors else print('Элемент отсутствует в списке!')
# Вывод: Элемент присутствует в списке!
Или можно ещё вот так:
colors = ['black', 'yellow', 'grey', 'brown']
if 'yellow' in colors: print('Элемент присутствует в списке!')
# Вывод: Элемент присутствует в списке!
Поиск с помощью лямбда функции
В переменную filtering будет сохранён итоговый результат. Обернём результат в список (list()), т.к. метода filter() возвращает объект filter. Отфильтруем все элементы списка, и оставим только искомый, если он конечно присутствует:
colors = ['black', 'yellow', 'grey', 'brown']
filtering = list(filter(lambda x: 'yellow' in x, colors))
Итак, если искомый элемент находился в списке, то он сохранился в переменную filtering. Создадим условие, что если переменная filtering не пустая, то выведем сообщение о присутствии элемента в списке. Иначе – отсутствии:
colors = ['black', 'yellow', 'grey', 'brown']
filtering = list(filter(lambda x: 'yellow' in x, colors))
if filtering:
print('Элемент присутствует в списке!')
else:
print('Элемент отсутствует в списке!')
# Вывод: Элемент присутствует в списке!
Поиск с помощью функции any()
Функция any принимает в качестве аргумента итерабельный объект, и возвращает True, если хотя бы один элемент равен True, иначе будет возвращено False.
Создадим условие, что если функция any() вернёт True, то элемент присутствует:
colors = ['black', 'yellow', 'grey', 'brown']
if any(color in 'yellow' for color in colors):
print('Элемент присутствует в списке!')
else:
print('Элемент отсутствует в списке!')
# Вывод: Элемент присутствует в списке!
Внутри функции any() при помощи цикла производится проверка присутствия элемента в списке.
Заключение
В ходе статьи мы с Вами разобрали целых 5 способов поиска элемента в списке Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂
try:
last_found = -1
for num in L1:
last_found = L2.index(num, last_found + 1)
return True
except ValueError:
return False
The index
method of list L2 returns the position at which the first argument (num
) is found in the list; called, like here, with a second arg, it starts looking in the list at that position. If index
does not find what it’s looking for, it raises a ValueError
exception.
So, this code uses this approach to look for each item num
of L1
, in order, inside L2
. The first time it needs to start looking from position 0; each following time, it needs to start looking from the position just after the last one where it found the previous item, i.e. last_found + 1
(so at the start we must set last_found = -1
to start looking from position 0 the first time).
If every item in L1 is found this way (i.e. it’s found in L2 after the position where the previous item was found), then the two lists meet the given condition and the code returns True
. If any item of L1 is ever not-found, the code catches the resulting ValueError
exception and just returns False
.
A different approach would be to use iterators over the two lists, that can be formed with the iter
built-in function. You can “advance” an iterator by calling built-in next
on it; this will raise StopIteration
if there is no “next item”, i.e., the iterator is exhausted. You can also use for
on the iterator for a somewhat smoother interface, where applicable. The low-level approach using the iter/next idea:
i1 = iter(L1)
i2 = iter(L2)
while True:
try:
lookfor = next(i1)
except StopIteration:
# no more items to look for == all good!
return True
while True:
try:
maybe = next(i2)
except StopIteration:
# item lookfor never matched == nope!
return False
if maybe == lookfor:
break
or, a bit higher-level:
i1 = iter(L1)
i2 = iter(L2)
for lookfor in i1:
for maybe in i2:
if maybe == lookfor:
break
else:
# item lookfor never matched == nope!
return False
# no more items to look for == all good!
return True
In fact, the only crucial use of iter
here is to get i2 — having the inner loop as for maybe in i2
guarantees the inner loop won’t start looking from the beginning every time, but, rather, it will keep looking where it last left off. The outer loop might as well for for lookfor in L1:
, since it has no “restarting” issue.
Key, here, is the else:
clause of loops, which triggers if, and only if, the loop was not interrupted by break
but rather exited naturally.
Working further on this idea we are again reminded of the in
operator, which also can be made to continue where it last left off simply by using an iterator. Big simplification:
i2 = iter(L2)
for lookfor in L1:
if lookfor not in i2:
return False
# no more items to look for == all good!
return True
But now we recognize that is exactly the patter abstracted by the short-circuiting any
and all
built-in “short-circuiting accumulator” functions, so…:
i2 = iter(L2)
return all(lookfor in i2 for lookfor in L1)
which I believe is just about as simple as you can get. The only non-elementary bit left here is: you need to use an iter(L2)
explicitly, just once, to make sure the in
operator (intrinsically an inner loop) doesn’t restart the search from the beginning but rather continues each time from where it last left off.
Время чтения 3 мин.
Существует несколько способов проверки наличия элемента в списке в Python:
- Использование метода index() для поиска индекса элемента в списке.
- Использование оператора in для проверки наличия элемента в списке.
- Использование метода count() для подсчета количества вхождений элемента.
- Использование функции any().
- Функция filter() создает новый список элементов на основе условий.
- Применение цикла for.
Содержание
- Способ 1: Использование метода index()
- Способ 2: Использование «оператора in»
- Способ 3: Использование функции count()
- Синтаксис
- Пример
- Способ 4: использование понимания списка с any()
- Способ 5: Использование метода filter()
- Способ 6: Использование цикла for
Способ 1: Использование метода index()
Чтобы найти элемент в списке Python, вы можете использовать метод list index(). Список index() — это встроенный метод, который ищет элемент в списке и возвращает его индекс.
Если один и тот же элемент присутствует более одного раза, метод возвращает индекс первого вхождения элемента.
Индекс в Python начинается с 0, а не с 1. Таким образом, через индекс мы можем найти позицию элемента в списке.
streaming = [‘netflix’, ‘hulu’, ‘disney+’, ‘appletv+’] index = streaming.index(‘disney+’) print(‘The index of disney+ is:’, index) |
Выход
The index of disney+ is: 2 |
Метод list.index() принимает единственный аргумент, элемент, и возвращает его позицию в списке.
Способ 2: Использование «оператора in»
Используйте оператор in, чтобы проверить, есть ли элемент в списке.
main_list = [11, 21, 19, 46] if 19 in main_list: print(“Element is in the list”) else: print(“Element is not in the list”) |
Выход
Вы можете видеть, что элемент «19» находится в списке. Вот почему оператор in возвращает True.
Если вы проверите элемент «50», то оператор in вернет False и выполнит оператор else.
Способ 3: Использование функции count()
Метод list.count() возвращает количество вхождений данного элемента в списке.
Синтаксис
Метод count() принимает единственный элемент аргумента: элемент, который будет подсчитан.
Пример
main_list = [11, 21, 19, 46] count = main_list.count(21) if count > 0: print(“Element is in the list”) else: print(“Element is not in the list”) |
Выход
Мы подсчитываем элемент «21», используя список в этой функции example.count(), и если он больше 0, это означает, что элемент существует; в противном случае это не так.
Способ 4: использование понимания списка с any()
Any() — это встроенная функция Python, которая возвращает True, если какой-либо элемент в итерируемом объекте имеет значение True. В противном случае возвращается False.
main_list = [11, 21, 19, 46] output = any(item in main_list for item in main_list if item == 22) print(str(bool(output))) |
Выход
Вы можете видеть, что в списке нет «22». Таким образом, нахождение «22» в списке вернет False функцией any(). Если функция any() возвращает True, элемент в списке существует.
Способ 5: Использование метода filter()
Метод filter() перебирает элементы списка, применяя функцию к каждому из них.
Функция filter() возвращает итератор, который перебирает элементы, когда функция возвращает значение True.
main_list = [11, 21, 19, 46] filtered = filter(lambda element: element == 19, main_list) print(list(filtered)) |
Выход
В этом примере мы используем функцию filter(), которая принимает функцию и перечисляет ее в качестве аргумента.
Мы использовали лямбда-функцию, чтобы проверить, совпадает ли входной элемент с любым элементом из списка, и если это так, он вернет итератор. Чтобы преобразовать итератор в список в Python, используйте функцию list().
Мы использовали функцию list() для преобразования итератора, возвращаемого функцией filter(), в список.
Способ 6: Использование цикла for
Вы можете узнать, находится ли элемент в списке, используя цикл for в Python.
main_list = [11, 21, 19, 46] for i in main_list: if(i == 46): print(“Element Exists”) |
Выход
В этом примере мы прошли список элемент за элементом, используя цикл for, и если элемент списка совпадает с входным элементом, он напечатает «Element exists».
In this article you will learn how to find the index of an element contained in a list in the Python programming language.
There are a few ways to achieve this, and in this article you will learn three of the different techniques used to find the index of a list element in Python.
The three techniques used are:
- finding the index using the
index()
list method, - using a
for-loop
, - and finally, using list comprehension and the
enumerate()
function.
Specifically, here is what we will cover in depth:
- An overview of lists in Python
- How indexing works
- Use the
index()
method to find the index of an item
1.Use optional parameters with theindex()
method - Get the indices of all occurrences of an item in a list
- Use a
for-loop
to get indices of all occurrences of an item in a list - Use list comprehension and the
enumerate()
function to get indices of all occurrences of an item in a list
- Use a
What are Lists in Python?
Lists are a built-in data type in Python, and one of the most powerful data structures.
They act as containers and store multiple, typically related, items under the same variable name.
Items are placed and enclosed inside square brackets, []
. Each item inside the square brackets is separated by a comma, ,
.
# a list called 'my_information' that contains strings and numbers
my_information = ["John Doe", 34, "London", 1.76]
From the example above, you can see that lists can contain items that are of any data type, meaning list elements can be heterogeneous.
Unlike arrays that only store items that are of the same type, lists allow for more flexibility.
Lists are also mutable, which means they are changeable and dynamic. List items can be updated, new items can be added to the list, and any item can be removed at any time throughout the life of the program.
An Overview of Indexing in Python
As mentioned, lists are a collection of items. Specifically, they are an ordered collection of items and they preserve that set and defined order for the most part.
Each element inside a list will have a unique position that identifies it.
That position is called the element’s index.
Indices in Python, and in all programming languages, start at 0
and not 1
.
Let’s take a look at the list that was used in the previous section:
my_information = ["John Doe", 34, "London", 1.76]
The list is zero-indexed and counting starts at 0
.
The first list element, "John Doe"
, has an index of 0
.
The second list element, 34
, has an index of 1
.
The third list element, "London"
, has an index of 2
.
The forth list element, 1.76
, has an index of 3
.
Indices come in useful for accessing specific list items whose position (index) you know.
So, you can grab any list element you want by using its index.
To access an item, first include the name of the list and then in square brackets include the integer that corresponds to the index for the item you want to access.
Here is how you would access each item using its index:
my_information = ["John Doe", 34, "London", 1.76]
print(my_information[0])
print(my_information[1])
print(my_information[2])
print(my_information[3])
#output
#John Doe
#34
#London
#1.76
But what about finding the index of a list item in Python?
In the sections that follow you will see some of the ways you can find the index of list elements.
So far you’ve seen how to access a value by referencing its index number.
What happens though when you don’t know the index number and you’re working with a large list?
You can give a value and find its index and in that way check the position it has within the list.
For that, Python’s built-in index()
method is used as a search tool.
The syntax of the index()
method looks like this:
my_list.index(item, start, end)
Let’s break it down:
my_list
is the name of the list you are searching through..index()
is the search method which takes three parameters. One parameter is required and the other two are optional.item
is the required parameter. It’s the element whose index you are searching for.start
is the first optional parameter. It’s the index where you will start your search from.end
the second optional parameter. It’s the index where you will end your search.
Let’s see an example using only the required parameter:
programming_languages = ["JavaScript","Python","Java","C++"]
print(programming_languages.index("Python"))
#output
#1
In the example above, the index()
method only takes one argument which is the element whose index you are looking for.
Keep in mind that the argument you pass is case-sensitive. This means that if you had passed “python”, and not “Python”, you would have received an error as “python” with a lowercase “p” is not part of the list.
The return value is an integer, which is the index number of the list item that was passed as an argument to the method.
Let’s look at another example:
programming_languages = ["JavaScript","Python","Java","C++"]
print(programming_languages.index("React"))
#output
#line 3, in <module>
# print(programming_languages.index("React"))
#ValueError: 'React' is not in list
If you try and search for an item but there is no match in the list you’re searching through, Python will throw an error as the return value – specifically it will return a ValueError
.
This means that the item you’re searching for doesn’t exist in the list.
A way to prevent this from happening, is to wrap the call to the index()
method in a try/except
block.
If the value does not exist, there will be a message to the console saying it is not stored in the list and therefore doesn’t exist.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
try:
print(programming_languages.index("React"))
except ValueError:
print("That item does not exist")
#output
#That item does not exist
Another way would be to check to see if the item is inside the list in the first place, before looking for its index number. The output will be a Boolean value – it will be either True or False.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print("React" in programming_languages)
#output
#False
How to Use the Optional Parameters with the index()
Method
Let’s take a look at the following example:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages.index("Python"))
#output
#1
In the list programming_languages
there are three instances of the “Python” string that is being searched.
As a way to test, you could work backwards as in this case the list is small.
You could count and figure out their index numbers and then reference them like you’ve seen in previous sections:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages[1])
print(programming_languages[3])
print(programming_languages[5])
#output
#Python
#Python
#Python
There is one at position 1
, another one at position 3
and the last one is at position 5
.
Why aren’t they showing in the output when the index()
method is used?
When the index()
method is used, the return value is only the first occurence of the item in the list. The rest of the occurrences are not returned.
The index()
method returns only the index of the position where the item appears the first time.
You could try passing the optional start
and end
parameters to the index()
method.
You already know that the first occurence starts at index 1
, so that could be the value of the start
parameter.
For the end
parameter you could first find the length of the list.
To find the length, use the len()
function:
print(len(programming_languages))
#output is 6
The value for end
parameter would then be the length of the list minus 1. The index of the last item in a list is always one less than the length of the list.
So, putting all that together, here is how you could try to get all three instances of the item:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
print(programming_languages.index("Python",1,5))
#output
#1
The output still returns only the first instance!
Although the start
and end
parameters provide a range of positions for your search, the return value when using the index()
method is still only the first occurence of the item in the list.
How to Get the Indices of All Occurrences of an Item in A List
Use a for-loop
to Get the Indices of All Occurrences of an Item in A List
Let’s take the same example that we’ve used so far.
That list has three occurrences of the string “Python”.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
First, create a new, empty list.
This will be the list where all indices of “Python” will be stored.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
Next, use a for-loop
. This is a way to iterate (or loop) through the list, and get each item in the original list. Specifically, we loop over each item’s index number.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
for programming_language in range(len(programming_languages)):
You first use the for
keyword.
Then create a variable, in this case programming_language
, which will act as a placeholder for the position of each item in the original list, during the iterating process.
Next, you need to specify the set amount of iterations the for-loop
should perform.
In this case, the loop will iterate through the full length of the list, from start to finish. The syntax range(len(programming_languages))
is a way to access all items in the list programming_languages
.
The range()
function takes a sequence of numbers that specify the number it should start counting from and the number it should end the counting with.
The len()
function calculates the length of the list, so in this case counting would start at 0
and end at – but not include – 6
, which is the end of the list.
Lastly, you need to set a logical condition.
Essentially, you want to say: “If during the iteration, the value at the given position is equal to ‘Python’, add that position to the new list I created earlier”.
You use the append()
method for adding an element to a list.
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = []
for programming_language in range(len(programming_languages)):
if programming_languages[programming_language] == "Python":
python_indices.append(programming_language)
print(python_indices)
#output
#[1, 3, 5]
Use List Comprehension and the enumerate()
Function to Get the Indices of All Occurrences of an Item in A List
Another way to find the indices of all the occurrences of a particular item is to use list comprehension.
List comprehension is a way to create a new list based on an existing list.
Here is how you would get all indices of each occurrence of the string “Python”, using list comprehension:
programming_languages = ["JavaScript","Python","Java","Python","C++","Python"]
python_indices = [index for (index, item) in enumerate(programming_languages) if item == "Python"]
print(python_indices)
#[1, 3, 5]
With the enumerate()
function you can store the indices of the items that meet the condition you set.
It first provides a pair (index, item
) for each element in the list (programming_languages
) that is passed as the argument to the function.
index
is for the index number of the list item and item
is for the list item itself.
Then, it acts as a counter which starts counting from 0
and increments each time the condition you set is met, selecting and moving the indices of the items that meet your criteria.
Paired with the list comprehension, a new list is created with all indices of the string “Python”.
Conclusion
And there you have it! You now know some of the ways to find the index of an item, and ways to find the indices of multiple occurrences of an item, in a list in Python.
I hope you found this article useful.
To learn more about the Python programming language, check out freeCodeCamp’s Scientific Computing with Python Certification.
You’ll start from the basics and learn in an interacitve and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.
Thanks for reading and happy coding!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started