1

After iterating through a list to change each value to an integer, the list remains unchanged with all the values still being strings.

As a result, sorting does not get applied either

a = ['14', '22', '4', '52', '54', '59']
for ea in a:
    ea = int(ea)
a.sort()
print (a)

Output: '14', '22', '4', '52', '54', '59' Should be : 4, 14, 22, 52, 54, 59

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
E Pak
  • 13
  • 2
  • 2
    Possible duplicate of [Python: list is not mutated after for loop](https://stackoverflow.com/questions/35874023/python-list-is-not-mutated-after-for-loop) – glibdud Sep 09 '19 at 19:08
  • if you just want to sort your list, look into `list.sort()` and `sorted(list)` – wcarhart Sep 09 '19 at 19:11

2 Answers2

1

ea = int(ea) is not changing the element within the list. So as you do not change the list (which can be seen if you print the list before sorting it), the sort operation is doing it's job correctly because it is sorting strings here, not integer values.

You could change your loop to provide the index and modify the original entries in the list by using the enumerate function as follows:

a = ['14', '22', '4', '52', '54', '59']

for index, ea in enumerate(a):
    a[index] = int(ea)

a.sort()
print(a)
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
1

Your code is not changing the list itself. You are creating a new variable, converting it to an int, and throwing it away.

Use this instead

a = ['14', '22', '4', '52', '54', '59']
a = list(map(int, a))  #this converts the strings into integers and assigns the new list to a
a.sort() #this sorts it
print (a)

Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35