Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: cannot unpack non-iterable int object (Python)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)]]

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading