1

I keep getting a TypeError 'Range' object does not support item assignment. I tried to change the code a little as in add iter(...) before the range, aswell as list(...) before range. However, it didn't help and the Error continues. Here's the code:

def findAnchor(anchors, node):
    start = node                   
    while node != anchors[node]:   
        node = anchors[node]       
    anchors[start] = node          
    return node

def unionFindConnectedComponents(graph):
    anchors = range(len(graph))        
    for node in iter(range(len(graph))):    
        for neighbor in graph[node]:   
            if neighbor < node:        
                continue

            a1 = findAnchor(anchors, node)       
            a2 = findAnchor(anchors, neighbor)   
            if a1 < a2:                          
                anchors[a2] = a1                 
            elif a2 < a1:                        
                anchors[a1] = a2                 

    labels = [None]*len(graph)         
    current_label = 0                  
    for node in range(len(graph)):
        a = findAnchor(anchors, node)  
        if a == node:                  
            labels[a] = current_label  
            current_label += 1         
        else:
            labels[node] = labels[a]   


    return anchors, labels

Now the TypeError is in the beginning at anchors[start] = node. And node is a given argument from the second function where it says for node in iter(range(len(graph))). I tried it with iter and with list, neither worked. What to do?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Mikail Cayoglu
  • 109
  • 2
  • 10

1 Answers1

6

anchors = range(len(graph)) generates a list in python 2 so you can assign to it.

But in python 3, the behaviour has changed. range becomes a lazy sequence generation object, which saves memory & CPU time because it is mostly used to count in loops and its usage to generate a contiguous actual list is rather rare.

From documentation:

Rather than being a function, range is actually an immutable sequence type

And such objects don't support slice assignment ([] operation)

Quickfix: force iteration on the range object, you'll get an object you can use slicing assignment to:

anchors = list(range(len(graph)))
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219