0
message = ["TS", "EE", "RE", "Z"]

So I'm trying to compare the characters within this list, and have conditions when some things arise such as if a value in the list for example "EE" is the same, it will return true and append a "Q" to separate the letters so the list looks like this

 message = ["TS", "EQ", "ER" "EZ"]

So I tried it normally without looping it works but when I loop it says string index out of range.

a = ''
a = message[1]
if a[0] == a[1]:
    print("True")
else:
    print("False")

When looping

for i in range(len(message)):
    a = ''
    a = message[i]
    if a[0] == a[1]:
        print("True")

What should I do? Turn it into a string first and work on it?

3
  • 1
    Your problem is the last element is length 1 so you tried to access the the second element when there is no second element i.e. Out of index error Commented Oct 1, 2017 at 4:22
  • Those a = '' lines are not accomplishing anything, since you replace the value of a on the next line. Commented Oct 1, 2017 at 4:27
  • For the last item in the array (the letter Z) there is no position 1 since the string only consists of 1 character. Commented Oct 1, 2017 at 4:28

1 Answer 1

1

Note that there is an element "Z" in the array (i.e. message[-1]) that has only one char in it.

def getIndex(message):
  for i in range(len(message)):
    a = message[i]
    if a[0] == a[1]:
      return i
index = getIndex(message)
tmp = message[index][1]
message[index][1] = 'Q'
for x in range(index+1, len(message)):
  tmp1 = message[x][0] 
  if len(message[x])==1:
    message[x][0] = tmp
    message[x][1] = tmp1
    return
  else:
    message[x][0] = tmp
    tmp = message[x][1]
    message[x][1] = tmp1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.