Search code examples
pythonint

TypeError "int" in Python


randsemiconclusion = [3234234, 234234, 23432]
wordstring = "                                                  "
liststr = list(wordstring)
for i in range(0, len(randsemiconclusion)):
    aw = randsemiconclusion[i]
    for j in range(0, 6):
        aac = int(i*7 + j+1)
        liststr[aac] = aw[j]
        wordstring = ''.join(liststr)
print("Wordstring -->  ", wordstring, "  <--")

Traceback:

Traceback (most recent call last):

liststr[aac] = aw[j]

TypeError: 'int' object is not subscriptable

(This is just an extractor the real code)

I am not sure as to why do I get the TypeError

This program is supposed to extract the numbers in the list and place them together in one string like so:

list[12, 23, 32]

to:

122332


Solution

  • You can rewrite the function like below:

    def concatenate_list_data(list):
        result= ''
        for element in list:
            result += str(element)
        return result
    
    my_result = concatenate_list_data([1, 5, 12, 2])   # leads to 15122
    

    Another approach to the same can be using a list comprehension:

    to_join = [1, 5, 12, 2]
    output = ''.join([str(i) for i in to_join])