0
def prepare_for_sort(st):
 nums = str(st).split()
 for each in nums:
    each = int(each)
 print(nums)

st is string with number like "20 50 4 8 4 64 6 47 8". Nums must be array of integer. Why this doesnt work?

keipa
  • 702
  • 1
  • 8
  • 17
  • `st` seems not to be what you expect it to be, because there's at least no error with `"20 50 4 8 4 64 6 47 8"` as input. Stil doesn't do what you want though – Felk Mar 08 '16 at 23:05
  • Even if you were properly making `nums` into a list of ints, you aren't **returning** anything from `prepare_for_sort`, so all your work is for nothing. – John Gordon Mar 08 '16 at 23:05

4 Answers4

0

This doesn't work because your variable each is a reference to some object: first, to the same object that's also contained in the list, then, to an integer object. each is, however, in no way connected to the list the content of which you want to manipulate.

You could manipulate the list in-place:

for index, value in enumerate(nums):
    nums[index] = int(value)

Or you can create a new list instead:

nums = [int(value) for value in nums]
Thomas Lotze
  • 5,153
  • 1
  • 16
  • 16
0

As you currently have it, you are attempting to modify the values in the list from inside of the for loop and this doesn't work because you are simply re-assigning the variable each within the for loop. The for loop will simply discard this value in order to assign each to the next item in the list. Any changes you make to each will be discarded as they are completely independent of the nums list.

You can actually accomplish your goal with a list comprehension.

nums = "20 50 4 8 4 64 6 47 8"
actual_nums = [int(n) for n in nums.split()]

Or if you actually want to do this in a loop. You can use indices for the loop so you can actually modify the list in place.

for k in range(len(nums)):
    nums[k] = int(nums[k]);
Suever
  • 64,497
  • 14
  • 82
  • 101
0

If you can in any way avoid it, don't modify the elements of a list while you're looping over it. It will only get you into trouble. Instead, try this:

def prepare_for_sort(st):
    nums = str(st).split()
    new_nums = []
    for each in nums:
        new_nums.append(int(each))
    print(new_nums)

Or, even shorter, using a list comprehension:

def prepare_for_sort(st):
    nums = str(st).split()
    new_nums = [int(x) for x in nums]
    print(new_nums)
Carsten
  • 17,991
  • 4
  • 48
  • 53
0

Try this:

def prepare_for_sort(st):
    nums = str(st).split()
    arrNums = [int(each) for each in nums]
    return arrNums

Of course that you will need to ensure that the string received by the function will always have only integer numbers and spaces.

Walter_Ritzel
  • 1,387
  • 1
  • 12
  • 16