0

My goal is to take a string and find the first occurance of each alphabetical letter and append it to a string. You would remove those letters from the original string and repeat until the original string is empty. For example, "aabdc" should return "abcad". To do this I split my string into a list and go through it checking for each letter. However, I keep getting an index out of range error because my for i in range(len(string)) keeps changing after I remove certain characters from the string. How would I fix this?

    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    def split(word):
      return list(word)

    def order(s):
      output = ""
      x = 0 
      s = split(s)
      for i in range(len(s)):
        if alphabet[x] not in s:
          x += 1
        if alphabet[x] == s[i]:
          output += s[i] 
          print(output)
          s.remove(s[i])
          print(s)
          x += 1
      return(output)
Coder1234
  • 11
  • 1
  • "How would I fix this?" -- by not mutating the list. – mustaccio Feb 28 '21 at 17:17
  • Does this answer your question? [Unexpected IndexError while removing list items](https://stackoverflow.com/questions/19312021/unexpected-indexerror-while-removing-list-items) – Reti43 Feb 28 '21 at 17:19
  • Also, see [How to make a list of the alphabet in Python](https://www.kite.com/python/answers/how-to-make-a-list-of-the-alphabet-in-python). – jarmod Feb 28 '21 at 17:20

2 Answers2

0

You are deleting list items while iterating, so its length reduces. You should use a copy of the list for searching letters.

Just create a copy of the list for the for cycle (i.e. s.copy()) then remove items for s during iterations.

frab
  • 1,162
  • 1
  • 4
  • 14
0

You only need to also decrease your variable named "i" when you remove an item in the list in order to keep it in order. check the following code:

 alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    def split(word):
      return list(word)

    def order(s):
      output = ""
      x = 0 
      s = split(s)
      i = 0
      while i < len(s):
        if alphabet[x] not in s:
          x += 1
        if alphabet[x] == s[i]:
          output += s[i] 
          print(output)
          s.remove(s[i])
          i = i - 1
          print(s)
          x += 1
      return(output)


Soroosh Khodami
  • 1,185
  • 9
  • 17