-1

I am trying to find the capital letters in a word and append their indexes in new list

eg:

Input           Output
pYtHoN          [1, 3, 5]
CApiTAls    [0, 1, 4, 5]

I created new list containing all the letters and checked if they are capital or not and append the result in a new list:

word = input()
word_list = list(word)

upper_case_list = []
for letter in word_list:
    if letter == letter.upper():
        upper_case_list.append(word_list.index(letter))

print(upper_case_list)

But my output is:

CApiTAls
[0, 1, 4, 1]

My output gives me the index 1 instead index 5:

['C', 'A', 'p', 'i', 'T', 'A', 'l', 's']

How can I get the actual index of A at index 5 and not repeated index 1?

Note: Im self-teaching to programming, also new.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Kuntov45
  • 1
  • 1

1 Answers1

2

Use enumerate to access the index while iterating. (list.index will only return the first index of an element.)

for index, letter in enumerate(word_list):
    if letter.isupper():
        upper_case_list.append(index)

Or, with a list comprehension:

upper_case_list = [index for index, letter in enumerate(word_list) if letter.isupper()]
Unmitigated
  • 76,500
  • 11
  • 62
  • 80