Как найти номер последнего элемента массива питон

In Python, how do you get the last element of a list?

To just get the last element,

  • without modifying the list, and
  • assuming you know the list has a last element (i.e. it is nonempty)

pass -1 to the subscript notation:

>>> a_list = ['zero', 'one', 'two', 'three']
>>> a_list[-1]
'three'

Explanation

Indexes and slices can take negative integers as arguments.

I have modified an example from the documentation to indicate which item in a sequence each index references, in this case, in the string "Python", -1 references the last element, the character, 'n':

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5 
  -6  -5  -4  -3  -2  -1

>>> p = 'Python'
>>> p[-1]
'n'

Assignment via iterable unpacking

This method may unnecessarily materialize a second list for the purposes of just getting the last element, but for the sake of completeness (and since it supports any iterable — not just lists):

>>> *head, last = a_list
>>> last
'three'

The variable name, head is bound to the unnecessary newly created list:

>>> head
['zero', 'one', 'two']

If you intend to do nothing with that list, this would be more apropos:

*_, last = a_list

Or, really, if you know it’s a list (or at least accepts subscript notation):

last = a_list[-1]

In a function

A commenter said:

I wish Python had a function for first() and last() like Lisp does… it would get rid of a lot of unnecessary lambda functions.

These would be quite simple to define:

def last(a_list):
    return a_list[-1]

def first(a_list):
    return a_list[0]

Or use operator.itemgetter:

>>> import operator
>>> last = operator.itemgetter(-1)
>>> first = operator.itemgetter(0)

In either case:

>>> last(a_list)
'three'
>>> first(a_list)
'zero'

Special cases

If you’re doing something more complicated, you may find it more performant to get the last element in slightly different ways.

If you’re new to programming, you should avoid this section, because it couples otherwise semantically different parts of algorithms together. If you change your algorithm in one place, it may have an unintended impact on another line of code.

I try to provide caveats and conditions as completely as I can, but I may have missed something. Please comment if you think I’m leaving a caveat out.

Slicing

A slice of a list returns a new list — so we can slice from -1 to the end if we are going to want the element in a new list:

>>> a_slice = a_list[-1:]
>>> a_slice
['three']

This has the upside of not failing if the list is empty:

>>> empty_list = []
>>> tail = empty_list[-1:]
>>> if tail:
...     do_something(tail)

Whereas attempting to access by index raises an IndexError which would need to be handled:

>>> empty_list[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

But again, slicing for this purpose should only be done if you need:

  • a new list created
  • and the new list to be empty if the prior list was empty.

for loops

As a feature of Python, there is no inner scoping in a for loop.

If you’re performing a complete iteration over the list already, the last element will still be referenced by the variable name assigned in the loop:

>>> def do_something(arg): pass
>>> for item in a_list:
...     do_something(item)
...     
>>> item
'three'

This is not semantically the last thing in the list. This is semantically the last thing that the name, item, was bound to.

>>> def do_something(arg): raise Exception
>>> for item in a_list:
...     do_something(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in do_something
Exception
>>> item
'zero'

Thus this should only be used to get the last element if you

  • are already looping, and
  • you know the loop will finish (not break or exit due to errors), otherwise it will point to the last element referenced by the loop.

Getting and removing it

We can also mutate our original list by removing and returning the last element:

>>> a_list.pop(-1)
'three'
>>> a_list
['zero', 'one', 'two']

But now the original list is modified.

(-1 is actually the default argument, so list.pop can be used without an index argument):

>>> a_list.pop()
'two'

Only do this if

  • you know the list has elements in it, or are prepared to handle the exception if it is empty, and
  • you do intend to remove the last element from the list, treating it like a stack.

These are valid use-cases, but not very common.

Saving the rest of the reverse for later:

I don’t know why you’d do it, but for completeness, since reversed returns an iterator (which supports the iterator protocol) you can pass its result to next:

>>> next(reversed([1,2,3]))
3

So it’s like doing the reverse of this:

>>> next(iter([1,2,3]))
1

But I can’t think of a good reason to do this, unless you’ll need the rest of the reverse iterator later, which would probably look more like this:

reverse_iterator = reversed([1,2,3])
last_element = next(reverse_iterator)

use_later = list(reverse_iterator)

and now:

>>> use_later
[2, 1]
>>> last_element
3

Getting the last element of the list is tricky while tracking each element, here we will discuss multiple methods to get the last element of the list. So we have given a list n, Our task is to get the last element of the list.

Example:

Input: [1, 2, 3, 4, 5, 5]
Output: 5

Input: ["Hello", "World"]
Output: World

Approaches to get the last element of list:

  • Using Reverse Iterator
  • Using negative indexing
  • Using list.pop()
  • Using reversed() + next() 
  • Using slicing
  • Using itemgetter

Using Reverse Iterator to get the last item of a list

To get the last element of the list using the naive method in Python. There can be 2-naive methods to get the last element of the list. 

  • Iterating the whole list and getting, the second last element.
  • Reversing the list and printing the first element.

Python3

test_list = [1, 4, 5, 6, 3, 5]

print("The original list is : " + str(test_list))

for i in range(0, len(test_list)):

    if i == (len(test_list)-1):

        print("The last element of list using loop : "

              + str(test_list[i]))

test_list.reverse()

print("The last element of list using reverse : "

      + str(test_list[0]))

Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element of list using loop : 5
The last element of list using reverse : 5

Using Negative Indexing to get the last element of list

To get last element of the list using the [] operator, the last element can be assessed easily if no. of elements in the list are already known. There is 2 indexing in Python that points to the last element in the list.

  • list[ len – 1 ] : This statement returns the last index if the list.
  • list[-1] : Negative indexing starts from the end.

Python3

test_list = [1, 4, 5, 6, 3, 5]

print("The original list is : " + str(test_list))

print("The last element using [ len -1 ] is : "

      + str(test_list[len(test_list) - 1]))

print("The last element using [ -1 ] is : "

      + str(test_list[-1]))

Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using [ len -1 ] is : 5
The last element using [ -1 ] is : 5

Get the last item of a list using list.pop()

To get the last element of the list using list.pop(), the list.pop() method is used to access the last element of the list. The drawback of this approach is that it also deletes the list’s last element, hence is only encouraged to use when the list is not to be reused. 

Python3

test_list = [1, 4, 5, 6, 3, 5]

print("The original list is : " + str(test_list))

print("The last element using pop() is : "

      + str(test_list.pop()))

Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using pop() is : 5

Get the last item of a list using reversed() + next() 

To get the last element of the list using reversed() + next(), the reversed() coupled with next() can easily be used to get the last element, as, like one of the naive methods, the reversed method returns the reversed ordering of list as an iterator, and next() method prints the next element, in this case, last element. 

Python3

test_list = [1, 4, 5, 6, 3, 5]

print("The original list is : " + str(test_list))

print("The last element using reversed() + next() is : "

      + str(next(reversed(test_list))))

Output :

The original list is : [1, 4, 5, 6, 3, 5]
The last element using reversed() + next() is : 5

Get the last item of a list by slicing

In this example, we will use list slicing to get the last element from the list.

Python3

test_list = [1, 4, 5, 6, 3, 5]

print("The original list is : " + str(test_list))

li = last_elem = test_list[-1:][0]

print("The last element using slicing is : ", li)

Output:

The original list is : [1, 4, 5, 6, 3, 5]
The last element using slicing is :  5

Get the last item of a list using itemgetter

The itemgetter can be used instead of lambda functions.  In terms of performance over time, itemgetter is better than lambda functions. When accessing many values, it appears more concise than lambda functions. Here, we will use itemgetter to get out the last element in the list.

Python3

import operator

test_list = [1, 4, 5, 6, 3, 5]

print("The original list is : " + str(test_list))

li = last_elem = operator.itemgetter(-1)(test_list)

print("The last element using itemgetter is : ", li)

Output:

The original list is : [1, 4, 5, 6, 3, 5]
The last element using itemgetter is :  5

Using deque from the collections module:

Algorithm:

  1. Convert the given list to a deque object.
  2. Use the pop() method to remove and return the last element of the deque object.
  3. Return the popped element as the result.

Python3

from collections import deque

test_list = [1, 4, 5, 6, 3, 5]

print("The original list is : " + str(test_list))

last_elem = deque(test_list).pop()

print("The last element using deque is : " + str(last_elem))

Output

The original list is : [1, 4, 5, 6, 3, 5]
The last element using deque is : 5

Complexity Analysis: The above code returns the last element of the given list using the deque.pop() method from the collections module. The time complexity of this approach is O(1) since the pop() operation on deque takes constant time, and the space complexity is O(n) since the deque object is created to store the list elements.

Last Updated :
22 Apr, 2023

Like Article

Save Article

Introduction

In this tutorial, we’ll take a look at some of the most common ways to find the last element in a list in Python. First, we will cover the simplest and most Pythonic way and then show some other alternative solutions afterward.

Let’s take a look at the list that we will be using:

exampleList = [1, 2, "Three", ["Four", 5], 6]

Note: A list in Python is a collection of elements that are not necessarily the same type. One list can contain elements that are numbers, strings, nested lists, etc.

How to Get the Last Element in a Python List

There’s several ways we can go about getting the last element of a list in Python — some of which are more intuitive and practical than others, and some of which actually change the original list in-place.

Winner Solution — Using Negative Indexing

Python supports the notion of negative indexing as the method of accessing list elements. This means that we can access elements in the reversed order by using the [] operator.

It’s well known how indexing in lists works:

firstElement = exampleList[0]
nthElement = exampleList[n-1]
...

The first element has the index of 0, the second has the index of 1, and the nth element has an index of n-1.

The negative indexing follows the same logic, but in reversed order. The last element has the index of -1, the second to last element has the index of -2, and so on:

lastElement = exampleList[-1]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

secondToLast = exampleList[-2]
print("Second to last element: ", secondToLast)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]
Second to last element:  ['Four', 5]

Negative indexing does not change the original list. It is only a way of accessing elements without any changes to the original list.

This is by far the simplest and most Pythonic solution, favored by most.

Using Indexing

Simple indexing is usually used to access elements in a list in the original order using the [] operator. As described above, the first element has an index of 0, the second element has an index of 1, and so on. Knowing that, we can conclude that the last element has the index of len(exampleList)-1:

lastElement = exampleList[len(exampleList)-1]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

secondToLast = exampleList[len(exampleList)-2]
print("Second to last element: ", secondToLast)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]
Second to last element:  ['Four', 5]

As well as negative indexing, the indexing method is only used to access elements of the list without performing any changes to the original list.

Using the pop() Method

In Python, the pop() method is used to remove the last element of the given list and return the removed item.

The pop() method can optionally accept an integer argument. It is the index of the element that we want to remove, so if we call exampleList.pop(0), the first element will be removed and returned.

If the argument is the negative number, the logic of the negative indexing will be performed to determine which element to remove. Calling exampleList.pop(-1) will result in removing the last element of the examleList.

Though, since the pop() method by default already pops the last element, there’s no real need to use indexing at all:

lastElement = exampleList.pop()
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5]]

Note that the pop() method, by definition, does change the original list by removing the popped element.

Using Slicing

In Python, the slicing notation is used to get a sublist of a list. The notation itself is pretty simple:

exampleList[startIndex:[endIndex[:indexStep]]]

This means that we can get the sublist of the exampleList with indices starting from startIndex, all the way to the endIndex with the step of indexStep.

The endIndex and indexStep are optional arguments. If we leave the endIndex blank, its default value is the end of the original list. The default value for indexStep is 1.

If we have a list letters=['a', 'b', 'c', 'd', 'e'] and slice it using letters[1:3] the resulting sublist will be ['b', 'c', 'd']. This means that we are choosing elements of the list letters with indices 1, 2, and 3.

letters[0:4:2] will return a sublist containing only elements on the even indices — 0, 2, 4.

The key feature of the slicing notation that we will be using is that it supports negative indexing.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This means that letters[-1:] can be interpreted as: get all elements in list letters, from the last element to the end of list letters. The resulting sublist will contain only the last element of the original list:

lastElement = exampleList[-1:][0]
# exampleList[-1:] alone will return the sublist - [6]
# exampleList[-1:][0] will return the last element - 6
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

The slicing method is only used to access elements of the list and to create a new list using them — without performing any changes to the original list.

Using the Reverse Iterator

Python has two built-in functions that we will use in this method — reversed() and next().

reversed() accepts a list as an argument and returns the reverse iterator for that list, meaning that the iteration is reversed, starting from the last element all the way to the first element. next() accepts an iterator and returns the next element from the iterator:

reversedIterator = reversed(exampleList)

lastElement = next(reversedIterator)
print("Last element: ", lastElement)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

The reversed iterator method is only used to access elements of the list in reverse order — without performing any changes to the original list.

Using the reverse() Method

The reverse() method is used to reverse the elements of the list. It does not take any arguments and does not return any value, instead, it reverses the original list in-place. This means that we can reverse the list and access the new first element:

# Update the original list by reversing its' elements
exampleList.reverse()

# Access the first element of the updated list
lastElement = exampleList[0]
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [6, ['Four', 5], 'Three', 2, 1]

The reverse() method, by definition, does change the original list by reversing the order of its elements. Please keep in mind that this approach may be a really inefficient overkill — since it takes time to reverse a list.

Using itemgetter()

The operator module provides a lot of efficient methods performing all of the fundamental operations in Python, such as the mathematical and logical operations, as well as other object comparison and sequence operations.

The itemgetter() method is one of the many methods in the operator module. It accepts one or more integers as the argument and returns a callable object which can be seen as a type of special function.

When we call operator.itemgetter(0), the resulting object will be a function that will get the first element in a collection. We can also assign a name to that object:

getFirstElement = operator.itemgetter(0)

Now, we can pass in a list to getFirstElement(people), which returns the first element from the list people.

The itemgetter() operator supports negative indexing so retrieving the last element boils down to:

import operator

getLastElement = operator.itemgetter(-1)
lastElement = getLastElement(exampleList)
print("Last element: ", lastElement)

print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

This approach doesn’t modify the original list — it generates a callable object that accesses it using indices.

Using Loops

Now, a much more manual and rudimentary approach would be using loops. We can iterate through the list, using the length of the list as the final step. Then, when on the len(list)-1 step — we can simply return that item:

for i in range(0, len(exampleList)):
    if i == (len(exampleList)-1) : lastElement = exampleList[i]
        
print("Last element: ", lastElement)
print("exampleList: ", exampleList)

Which outputs:

Last element:  6
exampleList:  [1, 2, 'Three', ['Four', 5], 6]

This also doesn’t change the list at all and simply accesses an element.

Conclusion

There are a lot of ways to get the last element in a list in Python. The main concern when choosing the right way for you is whether or not you want the last element to be removed.

If you need to get the last element without performing any changes to the original list, then the negative indexing method is the clear winner. It is the simplest and most Pythonic way to solve this problem.

On the other hand, if you need to remove the last element, as well as access it, then you should probably go with the pop() method, which is the built-in method for performing exactly this behavior.

Вступление

В этом руководстве мы рассмотрим некоторые из наиболее распространенных
способов найти последний элемент в списке в Python. Сначала мы
рассмотрим самый простой и наиболее питонический способ, а затем
покажем некоторые другие альтернативные решения.

Давайте посмотрим на список, который мы будем использовать:

 exampleList = [1, 2, "Three", ["Four", 5], 6] 

Примечание. Список в Python — это набор элементов, которые не
обязательно одного типа. Один список может содержать элементы, которые
являются числами, строками, вложенными списками и т. Д.

Как получить последний элемент в списке Python

Есть несколько способов получить последний элемент списка в Python —
некоторые из них более интуитивно понятны и практичны, чем другие, а
некоторые из них фактически изменяют исходный список на месте:

  • Использование отрицательной
    индексации — лучший
    подход
  • Использование индексации
  • Использование метода pop()
  • Использование нарезки
  • Использование обратного итератора
  • Использование метода reverse()
  • Использование itemgetter
  • Использование петель

Лучшее решение — использование отрицательной индексации

Python поддерживает понятие отрицательной индексации как метод
доступа к элементам списка. Это означает, что мы можем получить доступ к
элементам в обратном порядке , используя оператор []

Как работает индексация в списках, хорошо известно:

 firstElement = exampleList[0] 
 nthElement = exampleList[n-1] 
 ... 

Первый элемент имеет индекс 0 , второй имеет индекс 1 , а n й
элемент имеет индекс n-1 .

Отрицательная индексация следует той же логике, но в обратном порядке.
Последний элемент имеет индекс -1 , предпоследний элемент имеет индекс
-2 и так далее:

 lastElement = exampleList[-1] 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 
 
 secondToLast = exampleList[-2] 
 print("Second to last element: ", secondToLast) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 
 Second to last element: ['Four', 5] 

Отрицательная индексация не изменяет исходный список. Это всего лишь
способ доступа к элементам без каких-либо изменений в исходном списке.

Это, безусловно, самое простое и наиболее подходящее для Python решение.

Использование индексации

Простая индексация обычно используется для доступа к элементам в списке
в исходном порядке с помощью оператора [] Как описано выше, первый
элемент имеет индекс 0 , второй элемент имеет индекс 1 и так далее.
Зная это, мы можем сделать вывод, что последний элемент имеет индекс
len(exampleList)-1 :

 lastElement = exampleList[len(exampleList)-1] 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 
 
 secondToLast = exampleList[len(exampleList)-2] 
 print("Second to last element: ", secondToLast) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 
 Second to last element: ['Four', 5] 

Помимо отрицательной индексации, метод индексации используется только
для доступа к элементам списка без внесения каких-либо изменений в
исходный список.

Использование метода pop ()

В Python метод pop() используется для удаления последнего элемента
данного списка и возврата удаленного элемента.

Метод pop() может дополнительно принимать целочисленный аргумент.
Это индекс элемента, который мы хотим удалить, поэтому, если мы
вызовем exampleList.pop(0) , первый элемент будет удален и
возвращен.

Если аргумент — отрицательное число, будет выполнена логика
отрицательной индексации, чтобы определить, какой элемент удалить.
Вызов exampleList.pop(-1) приведет к удалению последнего элемента
examleList .

Хотя, поскольку метод pop() по умолчанию уже выталкивает последний
элемент
, нет никакой реальной необходимости использовать индексацию:

 lastElement = exampleList.pop() 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5]] 

Обратите внимание, что метод pop() по определению изменяет исходный
список
, удаляя всплывающий элемент.

Использование нарезки

В Python нотация срезов используется для получения подсписка списка.
Сама запись довольно проста:

 exampleList[startIndex:[endIndex[:indexStep]]] 

Это означает, что мы можем получить exampleList с индексами, начиная с
startIndex , вплоть до endIndex с шагом indexStep .

endIndex и indexStepнеобязательные аргументы. Если мы оставим
поле endIndex пустым, его значение по умолчанию будет концом исходного
списка. Значение по умолчанию для indexStep1 .

Если у нас есть список l=['a', 'b', 'c', 'd', 'e'] и нарезать его,
используя l[1:3] результирующий подсписок будет ['b', 'c', 'd'] .
Это означает, что мы выбираем элементы lits l с индексами
1, 2, and 3 .

l[0:4:2] вернет подсписок, содержащий только элементы с четными
индексами — 0, 2, 4 .

Ключевой особенностью нотации срезов, которую мы будем использовать,
является то, что она поддерживает отрицательную индексацию.

Это означает, что l[-1:] можно интерпретировать как: получить все
элементы в списке l , от последнего элемента до конца списка l
.
Результирующий подсписок будет содержать только последний элемент
исходного списка:

 lastElement = exampleList[-1:][0] 
 # exampleList[-1:] alone will return the sublist - [6] 
 # exampleList[-1:][0] will return the last element - 6 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 

Метод нарезки используется только для доступа к элементам списка и для
создания нового списка с их помощью — без внесения каких-либо изменений
в исходный список.

Использование обратного итератора

Python имеет две встроенные функции, которые мы будем использовать в
этом методе — reversed() и next() .

reversed() принимает список в качестве аргумента и возвращает обратный
итератор для этого списка, что означает, что итерация отменяется,
начиная с последнего элемента до первого элемента. next() принимает
итератор и возвращает следующий элемент из итератора:

 reversedIterator = reversed(exampleList) 
 
 lastElement = next(reversedIterator) 
 print("Last element: ", lastElement) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 

Обратный метод итератора используется только для доступа к элементам
списка в обратном порядке — без внесения каких-либо изменений в исходный
список.

Использование метода reverse ()

Метод reverse() используется для переворота элементов списка . Он
не принимает никаких аргументов и не возвращает никакого значения,
вместо этого он меняет исходный список на место . Это означает, что мы
можем перевернуть список и получить доступ к новому первому элементу:

 # Update the original list by reversing its' elements 
 exampleList.reverse() 
 
 # Access the first element of the updated list 
 lastElement = exampleList[0] 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [6, ['Four', 5], 'Three', 2, 1] 

Метод reverse() по определению изменяет исходный список, меняя порядок
его элементов. Имейте в виду, что такой подход может оказаться
действительно неэффективным излишеством, так как для переворота списка
требуется время.

Использование itemgetter ()

Модуль operator предоставляет множество эффективных методов,
выполняющих все основные операции в Python, такие как математические и
логические операции, а также другие операции сравнения объектов и
последовательности.

Метод itemgetter() — один из многих методов в модуле operator Он
принимает одно или несколько целых чисел в качестве аргумента и
возвращает вызываемый объект, который можно рассматривать как тип
специальной функции.

Когда мы вызываем operator.itemgetter(0) , результирующий объект будет
функцией, которая получит первый элемент в коллекции. Мы также можем
присвоить этому объекту имя:

 getFirstElement = operator.itemgetter(0) 

Теперь мы можем передать список в getFirstElement(l) , который
возвращает первый элемент из списка l .

Оператор itemgetter() поддерживает отрицательную индексацию,
поэтому получение последнего элемента сводится к следующему:

 import operator 
 
 getLastElement = operator.itemgetter(-1) 
 lastElement = getLastElement(exampleList) 
 print("Last element: ", lastElement) 
 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 

Этот подход не изменяет исходный список — он генерирует вызываемый
объект, который обращается к нему с помощью индексов.

Использование петель

Теперь гораздо более ручной и элементарный подход будет использовать
циклы. Мы можем перебирать список, используя длину списка в качестве
последнего шага. Затем, на len(l)-1 мы можем просто вернуть этот
элемент:

 for i in range(0, len(exampleList)): 
 if i == (len(exampleList)-1) : lastElement = exampleList[i] 
 
 print("Last element: ", lastElement) 
 print("exampleList: ", exampleList) 

Какие выходы:

 Last element: 6 
 exampleList: [1, 2, 'Three', ['Four', 5], 6] 

Это также не меняет список вообще, а просто получает доступ к элементу.

Заключение

Есть много способов получить последний элемент в списке в Python.
Основное беспокойство при выборе правильного для вас способа — погода
или нет, вы хотите, чтобы последний элемент был удален.

Если вам нужно получить последний элемент без внесения каких-либо
изменений в исходный список, то метод отрицательной индексации
является явным победителем. Это самый простой и самый питонический
способ решить эту проблему.

С другой стороны, если вам нужно удалить последний элемент, а также
получить к нему доступ, вам, вероятно, следует использовать метод
pop()
, который является встроенным методом для выполнения именно
этого поведения.

In this tutorial, you’ll learn how to use the Python list index method to find the index (or indices) of an item in a list. The method replicates the behavior of the indexOf() method in many other languages, such as JavaScript. Being able to work with Python lists is an important skill for a Pythonista of any skill level. We’ll cover how to find a single item, multiple items, and items meetings a single condition.

By the end of this tutorial, you’ll have learned:

  • How the Python list.index() method works
  • How to find a single item’s index in a list
  • How to find the indices of all items in a list
  • How to find the indices of items matching a condition
  • How to use alternative methods like list comprehensions to find the index of an item in a list

Python List Index Method Explained

The Python list.index() method returns the index of the item specified in the list. The method will return only the first instance of that item. It will raise a ValueError is that item is not present in the list.

Let’s take a look at the syntax of the index() method:

# The list.index() Method Explained
list.index(
    element,    # The element to search for
    start,      # The index to start searching at
    end         # The index to end searching at
)

Let’s break these parameters down a little further:

  • element= represents the element to be search for in the list
  • start= is an optional parameter that indicates which index position to start searching from
  • end= is an optional parameter that indicates which index position to search up to

The method returns the index of the given element if it exists. Keep in mind, it will only return the first index. Additionally, if an item doesn’t exist, a ValueError will be raised.

In the next section, you’ll learn how to use the .index() method.

Find the Index Position of an Item in a Python List

Let’s take a look at how the Python list.index() method works. In this example, we’ll search for the index position of an item we know is in the list.

Let’s imagine we have a list of the websites we open up in the morning and we want to know at which points we opened 'datagy'.

# Finding the index of an item in a list
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(a_list.index('datagy'))

# Returns: 0

We can see that the word 'datagy' was in the first index position. We can see that the word 'twitter' appears more than once in the list. In the next section, you’ll learn how to find every index position of an item.

Finding All Indices of an Item in a Python List

In the section above, you learned that the list.index() method only returns the first index of an item in a list. In many cases, however, you’ll want to know the index positions of all items in a list that match a condition.

Unfortunately, Python doesn’t provide an easy method to do this. However, we can make use of incredibly versatile enumerate() function and a for-loop to do this. The enumerate function iterates of an item and returns both the index position and the value.

Let’s see how we can find all the index positions of an item in a list using a for loop and the enumerate() function:

# Finding all indices of an item in a list
def find_indices(search_list, search_item):
    indices = []
    for (index, item) in enumerate(search_list):
        if item == search_item:
            indices.append(index)

    return indices

a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'twitter'))

# Returns: [1, 3]

Let’s break down what we did here:

  1. We defined a function, find_indices(), that takes two arguments: the list to search and the item to find
  2. The function instantiates an empty list to store any index position it finds
  3. The function then loops over the index and item in the result of the enumerate() function
  4. For each item, the function evaludates if the item is equal to the search term. If it is, the index is appended to the list
  5. Finally, this list is returned

We can also shorten this list for a more compact version by using a Python list comprehension. Let’s see what this looks like:

# A shortened function to return all indices of an item in a list
def find_indices(search_list, search_item):
    return [index for (index, item) in enumerate(search_list) if item == search_item]

a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'twitter'))

# Returns: [1, 3]

One of the perks of both these functions is that when an item doesn’t exist in a list, the function will simply return an empty list, rather than raising an error.

Find the Last Index Position of an Item in a Python List

In this section, you’ll learn how to find the last index position of an item in a list. There are different ways to approach this. Depending on the size of your list, you may want to choose one approach over the other.

For smaller lists, let’s use this simpler approach:

# Finding the last index position of an item in a list
def find_last_index(search_list, search_item):
    return len(search_list) - 1 - search_list[::-1].index(search_item)

a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

print(find_last_index(a_list, 'twitter'))

# Returns: 3

In this approach, the function subtracts the following values:

  • len(search_list) returns the length of the list
  • 1, since indices start at 0
  • The .index() of the reversed list

There are two main problems with this approach:

  1. If an item doesn’t exist, an ValueError will be raised
  2. The function makes a copy of the list. This can be fine for smaller lists, but for larger lists this approach may be computationally expensive.

Let’s take a look at another approach that loops over the list in reverse order. This saves the trouble of duplicating the list:

# A less simple, but more memory efficient way of finding the last index of an item
def find_last_index(search_list, search_item):
    i = len(search_list) - 1
    while i >= 0:
        if search_list[i] == search_item:
            return i
        else:
            i -= 1
            
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

print(find_last_index(a_list, 'twitter'))

# Returns: 3

In the example above we loop over the list in reverse, by starting at the last index. We then evaluate if that item is equal to the search term. If it is we return the index position and the loop ends. Otherwise, we decrement the value by 1 using the augmented assignment operator.

Index of an Element Not Present in a Python List

By default, the Python list.index() method will raise a ValueError if an item is not present in a list. Let’s see what this looks like. We’ll search for the term 'pinterest' in our list:

# Searching for an item that doesn't exist
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

print(a_list.index('pinterest'))

# Raises: ValueError: 'pinterest' is not in list

When Python raises this error, the entire program stops. We can work around this by nesting it in a try-except block.

Let’s see how we can handle this error:

# Handling an error when an item doesn't exist
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

try:
    print(a_list.index('pinterest'))
except ValueError:
    print("Item doesn't exist!")

# Returns: Item doesn't exist!

Working with List Index Method Parameters

The Python list.index() method also provides two additional parameters, start= and stop=. These parameters, respectively, indicate the positions at which to start and stop searching.

Let’s say that we wanted to start searching at the second index and stop at the sixth, we could write:

# Using Start and Stop Parameters in list.index()
a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']

print(a_list.index('twitter', 2, 6))

# Returns: 3

By instructing the method to start at index 2, the method skips over the first instance of the string 'twitter'.

Finding All Indices of Items Matching a Condition

In this final section, we’ll explore how to find the index positions of all items that match a condition. Let’s say, for example, that we wanted to find all the index positions of items that contain the letter 'y'. We could use emulate the approach above where we find the index position of all items. However, we’ll add in an extra condition to our check:

# Finding Indices of Items Matching a Condition
def find_indices(search_list, search_item):
    return [index for (index, item) in enumerate(search_list) if search_item in item]


a_list = ['datagy', 'twitter', 'facebook', 'twitter', 'tiktok', 'youtube']
print(find_indices(a_list, 'y'))

# Returns:
# [0, 5]

The main difference in this function to the one shared above is that we evaluate on a more “fuzzy” condition.

Conclusion

In this tutorial, you learned how to use the index list method in Python. You learned how the method works and how to use it to find the index position of a search term. You also learned how to find the index positions of items that exist more than once, as well as finding the last index position of an item.

Finally, you learned how to handle errors when an item doesn’t exist as well as how to find the indices of items that match a condition.

Additional Resources

To learn more about related topics, check out the tutorials below:

  • Python Lists: A Complete Overview
  • Python Zip Lists – Zip Two or More Lists in Python
  • Python IndexError: List Index Out of Range Error Explained
  • Python List Index: Official Documentation

Понравилась статья? Поделить с друзьями:
  • Как составить план ловушек
  • Как найти площу с 2 сторонами
  • Как исправить провисшие двери на машине
  • Как составить апелляцию на решение суда образцы
  • Как по поиску найти файл в папке