-1

I some lines of code in order to prep the data to be sorted. In order to do this, I needed each item in the list to be a list. For example, if my list was [a, b, c, d], the list should be become [[a], [b], [c], [d]] where a, b, c, and d are integers. My code however returns [[d], [d], [d], [d]]:

len_of_list = random.randint(8500, 10000)
val_list = range(len_of_list)

list_one = [[-1]]
for index in range(0, len_of_list):
    list_one[0][0] = val_list[index]
    val_list[index] = list_one[0]
print val_list

The weirdest thing that happens to the code is that when the second-to-last line is replaced with val_list[index] = list_one[0][0], it returns the correct values just without the []. Thus I assumed that removing the last [0] would return the values with the [] around them. But what is returned was the last integer in the list originally surrounded by [] for all values. This shouldn't happen because list[0][0] is reset every iteration with list[0][0] = val_list[index].

So why is the list being returned as [[d], [d], [d], [d]] instead of [[a], [b], [c], [d]]. Of course, the list has at least 8500 unique integers but d represents the last value in the list or put simply d = val_list[len(val_list) - 1].

martineau
  • 119,623
  • 25
  • 170
  • 301
Anthony Pham
  • 3,096
  • 5
  • 29
  • 38

2 Answers2

1

Try this:

[[x] for x in myList]
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38
1

You put list_one[0] in val_list[index]. Since list_one[0] is a list, val_list[index] receives its address, not its value. Therefore, when the value of list_one[0] is changed, ie. at every iteration, the value of val_list[index] for every index is changed as well.

Thus, the final value contained at every index of the list is the last one, [d].

This happens because list_one[0] is a list, which is mutable.


Beyond this fact, your code is not really pythonic. First, you build an empty list of length len_of_list by writing val_list = range(len_of_list). While this works in Python 2, it does not in Python 3, because a range object is semantically different from a list. Besides, a list should be built by appending or inserting elements, but not by making a long enough empty list and then filling the indices.

Then, you are using complicated code to build your list of list, while the following would have been enough:

for index in range(len_of_list):
    val_list[index] = [index]

A more basic pythonic way to do the same, with append, would be:

len_of_list = random.randint(8500, 10000)
val_list = list()

for index in range(len_of_list):
    val_list.append([index])

However, the most pythonic way would be to use a list comprehension. If you have l = [a, b, c, d], and you want to have [[a], [b], [c], [d]], the fastes is the following:

[[elt] for elt in l]
Right leg
  • 16,080
  • 7
  • 48
  • 81