Home > Software design >  TypeError: cannot unpack non-iterable int object (Python)
TypeError: cannot unpack non-iterable int object (Python)

Time:07-03

I am trying to add (0.5,-0.5) to (i,j) elements in the list I4 but there is an error. I present the expected output.

I3 = [[(0, 0), (0, 1)], [(0, 0), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (1, 1)]]
temp = []
for t in range(0,len(I3)):
    I4 = [(j, -i) for i, j in I3[t]]
    temp.append(I4)
print("I4 =",temp)
#I4 = [[(0, 0), (1, 0)], [(0, 0), (0, -1)], [(1, 0), (1, -1)], [(0, -1), (1, #-1)]]

temp2 = []
for h in range(0,len(I3)):
    I5 = [(i 0.5, j-0.5) for i, j in I4[h]]
    temp2.append(I5)
print("I5 =",temp2)

The error is

in <listcomp>
    I5 = [(i 0.5, j-0.5) for i, j in I4[h]]

TypeError: cannot unpack non-iterable int object

The expected output is

I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5), (1.5, -1.5)]]

CodePudding user response:

You seems to misunderstand a thing print("I4 =",temp), I4 was just ONE element you added to temp,

And you heave repeated the mistake later

I5 = [(i 0.5, j-0.5) for i, j in I4[h]]    # error
I5 = [(i 0.5, j-0.5) for i, j in temp[h]]  # correct
                                  ^

You can use a better naming, iteration on value, and avoid variable that you can inline easily, that can fail you to right propre (as you did with I4)

temp = []
for sublist in I3:
    temp.append([(j, -i) for i, j in sublist])

temp2 = []
for sublist in temp:
    temp2.append([(i   0.5, j - 0.5) for i, j in sublist])

You can use list comprehension

temp = [[(j, -i) for i, j in sublist] for sublist in I3]
temp2 = [[(i   0.5, j - 0.5) for i, j in sublist] for sublist in temp]

You can use one list comprehension

result = [[(j   0.5, -i - 0.5) for i, j in sublist] for sublist in I3]

CodePudding user response:

Your code seems to be failing due to a misplaced # character on I4 list and a wrong iteration over I4, which should be I3 instead:

I3 = [[(0, 0), (0, 1)], [(0, 0), (1, 0)], [(0, 1), (1, 1)], [(1, 0), (1, 1)]]
temp = []
for t in range(0,len(I3)):
    I4 = [(j, -i) for i, j in I3[t]]
    temp.append(I4)
print("I4 =",temp)

temp2 = []
for h in range(0,len(I3)):
    I5 = [(i 0.5, j-0.5) for i, j in I3[h]]
    temp2.append(I5)
print("I5 =",temp2)

Output:

I4 = [[(0, 0), (1, 0)], [(0, 0), (0, -1)], [(1, 0), (1, -1)], [(0, -1), (1, -1)]]
I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5), (1.5, -1.5)]]

CodePudding user response:

The second part of the code should be

for h in range(0,len(I3)):
    I5 = [(i 0.5, j-0.5) for i, j in temp[h]]
    temp2.append(I5)

print("I5 =",temp2)

Replace I4 with temp should solve the issue here.

  • Related