Search code examples
pythonlistindex-error

I just want to get same index letter for each element on my list


For ex:

a = "pandaxngeqrymtso-ezmlaesowxaqbujl-noilktxreecytrql-gskaboofsfoxdtei-utsmakotufodhlrd-iroachimpanzeesa-nintrwflyrkhcdum-jcecahkktiklsvhr-mhvsbaykagodwgca-koalatcwlkfmrwbb-jsrrfdolphinuyt"

a = a.split("-") 

mylist = []

word = ""

while i < len(a[0]): #16

      for elem in a:
        word+= elem[i]
  mylist.append(kelime)

  i += 1

  word = "" 

I just want a list which contains "penguinjmhkj, azostrichos..." But I get an Index error. What can I do?


Solution

  • it took a while but i cracked it;

    what you just need to do is to handle the Index Error: String out of range.

    if you count the words they are over 16 while the array items after splitting are just over 11. to cut long story short; Handle the exception with a try_except where you are appending the letters at:

     word+= elem[i]
    

    here is my code and how i solved it using try_catch

    a = "pandaxngeqrymtso-ezmlaesowxaqbujl-noilktxreecytrql-gskaboofsfoxdtei-utsmakotufodhlrd-iroachimpanzeesa-nintrwflyrkhcdum-jcecahkktiklsvhr-mhvsbaykagodwgca-koalatcwlkfmrwbb-jsrrfdolphinuyt"
    newArr = a.split('-')
    newWord = []
    i = 0
    mylist = []
    while i < len(newArr[0]):
        word = ""
        for item in newArr:
           try:
                word  += item[i]
           except:
                break
        i += 1
        mylist.append(word)
    print(mylist)
    
    
    

    I used a try_except to handle the Index Error when appending the letter, then break when ever the 'i' used for the while loop is greater than the newArr length in the for loop.

    try for your self!