0
sharief
4y

n=input( )
k=list(n)
for j in range(len(k)):
if k[j]=="a":

k.pop(j)
print(k)
''' i want to print the list by removing a letter "a" but it is showing index error why ? help me out'''

Comments
  • 2
    You don't have to cast your input "n" to a list. Your input will be a string and in essence a string is just a list of characters.

    So you could do the following:

    n = input()

    for char in n:

    if char == "a":

    # do your thing
  • 1
    @TipsyTapir that's a rather inconvenient way to do it. I would use string replace with a count of 1, if his question was worded correctly.

    @highlight
    print(input().replace("a", "", 1))
  • 1
  • 0
    okay ... but why iam getting that error ..even the range is not crossing the index
  • 1
    @TipsyTapir While Python Strings are iterable and indexable, they are also immutable

    @sharief
    You modify the list you are iterating over. I will show you what happens (this is pseudocode, obviously):

    n = "bar"
    k=['b', 'a', 'r']
    len(n) == 3

    Steps of for j in range(3):
    j = 0; k[0] = 'b'
    j = 1; k[1] = 'a'; k.pop('a'); k = ['b', 'r']
    j = 2; k[2] โฌ…IndexError happens here, as k only has two elements, and not three.

    What could you do instead?

    Python Strings have a .replace method (e.g. n = n.replace("a", "").

    Alternatively (if you don't actually have a string, but a list if something else) you could also do this:

    while "a" in k:
    k.pop(k.index("a"))
  • 1
    thank you ๐Ÿ˜€๐Ÿ˜€๐Ÿ˜€๐Ÿ˜€
  • 2
    @p100sch Yep should have read the complete question. I was more focusing on the index out of range error. Should have noticed he just wanted to replace some value. My bad ๐Ÿ˜œ
Add Comment