Count number of elements from a python list

Asked

Viewed 8,133 times

1

I have the following list:

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

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

  • A for wouldn’t solve your problem?

  • but like I used to count up to C just as example, I want to ask a question, and count up to the letter that the person answer

  • But this to make it go, I’ll give you an answer as an example for you

  • I would answer, but Marcos . p, made a better code than mine

  • 1

    @Wictorchaves his answer is different and also from the result expected by him, more than one solution is always welcome! :D

  • 1

    What if there is repeated data in the list? For example, ['a', 'b', 'c', 'd', 'c'], the result should be 3 or 5? You should always consider the first occurrence?

Show 1 more comment

3 answers

3


Just take the index and add up to 1, since the first index is 0.

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

To pick the index of the array use the method "index".

2

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

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

0

Another way would be to use the for, as Wictor proposes 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() Wictor’s answer is simpler and more elegant.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.