how to get index of a giving string in liste python?

Question:

my list is like this, in example the string is ‘a’ and ‘b’ ;
i want to return the index of string ‘a’ and for ‘b’ then i want to calculate how many time is ‘a’ repeated in the list1 :

list1=['a','a','b','a','a','b','a','a','b','a','b','a','a']

i want to return the order of evry ‘a’ in list1
the result should be like this :

a_position=[1,2,4,5,7,8,10,12,13]

and i want to calculate how many time ‘a’ is repeated in list1:
a_rep=9

Asked By: phœnix

||

Answers:

If you want to get the indices and counts of all letters:

list1=['a','a','b','a','a','b','a','a','b','a','b','a','a']
pos = {}
for i,c in enumerate(list1, start=1): # 1-based indexing
    pos.setdefault(c, []).append(i)
pos
# {'a': [1, 2, 4, 5, 7, 8, 10, 12, 13],
#  'b': [3, 6, 9, 11]}

counts = {k: len(v) for k,v in pos.items()}
# {'a': 9, 'b': 4}
Answered By: mozway

You could do below:

a_positions = [idx + 1 for idx, el in enumerate(list1) if el == 'a']
a_repitition = len(a_positions)

print(a_positions):

[1, 2, 4, 5, 7, 8, 10, 12, 13]

print(a_repitition):

9

If you need repititions of each element you can also use collections.Counter

from collections import Counter
counter = Counter(list1)

print(counter[‘a’]):

9
Answered By: SomeDude
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.