eibb95
eibb95

Reputation: 23

My Python for loop is giving the result None

In code below, this loop is supposed to take a tuple, say (1,2,3), a key from a dictionary, turn it into a list, [1,2,3], stick a 1 on the end, [1,2,3,1] and, for each key, add this new list to a longer list called new_training_data.

This is what I have written:

my_training_data={
    (1,2,3,4):[1,0,0],
    (1.2,1.8,3.2,3.8):[1,0,0],
    (1.1,1.9,3.1,3.9):[1,0,0],
    (4,3,2,1):[0,1,0],
    (3.8,3,2,1.8,1.2):[0,1,0],
    (3.9,3.1,1.9,1.1):[0,1,0]
}
def part_1(my_training_data):
   for key in sorted(my_training_data):
       new_training_data=[]
       new_training_data=new_training_data.append(list(key).extend([1]))
   return new_training_data

And when I type

print part_1(my_training_data)

I get the result None.

Please help! I've been struggling with this for a while.

PS. I am writing this in IPython, having downloaded Anaconda for 64 bit Windows, version 2.7.

Upvotes: 0

Views: 525

Answers (2)

Anshul Goyal
Anshul Goyal

Reputation: 76887

You are reinitializing new_training_data in every run of the for loop, move it out. Also, the result of list(key).extend([1]) is None (as in None is returned), so the list will contain only a single None in the final iteration.

So, do the following:

def part_1(my_training_data):
   new_training_data=[]
   for key in sorted(my_training_data):
       new_training_data.append(list(key) + [1])
   return new_training_data

Edit: Complete run

>>> my_training_data={
...     (1,2,3,4):[1,0,0],
...     (1.2,1.8,3.2,3.8):[1,0,0],
...     (1.1,1.9,3.1,3.9):[1,0,0],
...     (4,3,2,1):[0,1,0],
...     (3.8,3,2,1.8,1.2):[0,1,0],
...     (3.9,3.1,1.9,1.1):[0,1,0]
... }
>>> def part_1(my_training_data):
...    new_training_data=[]
...    for key in sorted(my_training_data):
...        new_training_data.append(list(key) + [1])
...    return new_training_data
... 
>>> part_1(my_training_data)
[[1, 2, 3, 4, 1], [1.1, 1.9, 3.1, 3.9, 1], [1.2, 1.8, 3.2, 3.8, 1], [3.8, 3, 2, 1.8, 1.2, 1], [3.9, 3.1, 1.9, 1.1, 1], [4, 3, 2, 1, 1]]

Upvotes: 3

Jaakko
Jaakko

Reputation: 584

if I understood correctly your questions, this is what you are apparently looking for:

def part_1(my_training_data):
    new_training_data = []
    for key in sorted(my_training_data):
        new_training_data.append(list(key)+[1])
    return new_training_data

Upvotes: 1

Related Questions