Count number of elements in a python list

1

I have the following list:

lista = [ 'A','B','C','D']

I want to count the number of elements to a certain point, I know that if you do len(lista) it will count all the elements but what I want is for example until C it will give me the number 3.

    
asked by anonymous 06.12.2018 / 13:57

3 answers

3

Just take the index and add it with 1 more, since the first index is 0.

lista = ['A','B','C','D']
print lista.index('C') + 1;
  

To get the array index use the "index" method.

    
06.12.2018 / 14:20
2

You can use the index to find the position of the desired element and calculate the quantity discounting from the total elements, for example:

lista = [ 'A','B','C','D']
indice = lista.index('C')
(indice + 1)
    
06.12.2018 / 14:08
0

Another way would be to use for, as Wictor proposed in the comments:

i = 0
lista = [ 'A','B','C','D']

for x in lista:
  i+=1
  if x == 'C':
    break;
print(i)

But using index() of Wictor's response is simpler and more elegant.

    
06.12.2018 / 14:33