0

This is my code:

word = str(input())
list = []

for i in range(len(word)):
    B = word[i]
    list.append(B)

D = list.pop(0)
E = D.upper()
list.insert(0, E)



capitalized_word = ""
for i in range(0, len(list)):
    C = list.pop(i)
    capitalized_word = capitalized_word + C


print(capitalized_word)

This is the error i am getting:

wORd
Traceback (most recent call last):
  File "/Users/akarsh/Desktop/python/capitalization.py", line 16, in <module>
    C = list.pop(i)
IndexError: pop index out of range

Here i is taking values from 0 to 3 which is in the range of index of the list but still i am getting this error

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
R.singh
  • 11
  • 2
  • 1
    The list becomes shorter with each iteration, but the indexes are up to its original length. – bereal Aug 11 '18 at 07:30

3 Answers3

0

You're popping the former values from 0 to 3 from the list. Once those values are popped, the list is smaller.

Hans Musgrave
  • 6,613
  • 1
  • 18
  • 37
0

This is because list.pop modifies original list, and range(len(word)) is calculated only once in the beginning of the loop.

So you asked for a better way to do it. Use str.join() function to concat strings in a list. Like this:

capitalized_word = "".join(list)
leotrubach
  • 1,509
  • 12
  • 15
0

First, don't call your variable list. It is a Python built-in type and using the name for something else it will cause you baffling problems.

To start with, this

word = str(input())
list = []

for i in range(len(word)):
    B = word[i]
    list.append(B)

is a very cumbersome way to turn a string into a list. Do it this way instead:

>>> word = "fred"
>>> mylist = list(word)
>>> mylist
['f', 'r', 'e', 'd']

To capitalize each word in the list, don't use pop() because it changes the length of the list, and your expression range(0, len(list)) assumes the length won't change. There is no need to extract your letter from the list in order to build up capitalized_word:

>>> capitalized_word = ""
>>> for c in mylist:
    capitalized_word += c
>>> capitalized_word
'fred'

You will note that this is in fact not capitalized because your code doesn't actually upshift it. To achieve that,

>>> capitalized_word = ""
>>> for c in mylist:
    capitalized_word += c.upper()
>>> capitalized_word
'FRED'

This shows you why your method isn't working, but it is not the best approach to working with strings in Python. Don't actually do it this way. Use built-in facilities instead:

>>> word = "fred"
>>> capitalized_word = word.upper()
>>> capitalized_word
'FRED'

Similiarly, don't do this to provide an initial capital:

D = list.pop(0)
E = D.upper()
list.insert(0, E)

Instead do this:

>>> word = "fred"
>>> capitalized_word = word.title()
>>> capitalized_word
'Fred'
BoarGules
  • 16,440
  • 2
  • 27
  • 44