Search code examples
pythonlistnonetype

TypeError: 'NoneType' object is not subscriptable, Python


I need to count the number of pairs of elements that are equal to each other

list1 = input("Введите список: ")
list2 = list1.split()
list3 = []
counter = 0
for i in range(0, (len(list2))):
    element = list2[i]
    if element == "":
        pass
    elif list2.count(element)//2 >= 1:
        counter += list2.count(element)//2
        for a in range(0, (len(list2))):
            if list2[a] != element:
                list2 = list3.append(list2[a])
            else:
                list2 = list3.append("")
    else:
        pass
print(list2)
print(counter)

error:

    if list2[a] != element:
TypeError: 'NoneType' object is not subscriptable

I don't understand what it wants from me and what I did wrong


Solution

  • Code can also be as follows:

    words = input("Введите список: ").split()
    
    list3 = []
    counter = 0
    counted_words = set()
    
    for element in words:
        if element != "" and element not in counted_words:
            counted_words.add(element)
            c = words.count(element) // 2
            if c >= 1:
                counter += c
                list3.extend(['' if w == element else w for w in words])
    
    print(list3)
    print(counter)