-1

I am still a newbie in programming and I need some help I want to substract 9 from numbers bigger then 9 from a list.

ls = [1, 2, 3, 4 ,5, 6, 7, 8, 9]
odd_num = []
for _ in ls[::2]:
    odd_num.append(_)
    ls.remove(_)    
for _ in odd_num:
    multip_elem = _ * 2
    ls.append(multip_elem)
for _ in ls:
    if _ > 9:
        substraction = _ - 9
        ls.append(substraction)
        ls.remove(_)
print(ls)

This is the output

[2, 4, 6, 8, 2, 6, 14, 1, 9]

14 is still in the list but I am pretty sure is bigger then 9 :))

  • 1
    [Avoid modifying lists while iterating over them.](https://stackoverflow.com/questions/1637807/modifying-list-while-iterating) – John Kugelman Mar 21 '21 at 14:16

3 Answers3

0
ls = [1, 2, 3, 4 ,5, 6, 7, 8, 9, 10, 11]
ls = [i-9 if i>9 else i for i in ls]
print(ls)

A pythonic way of turning one list into other. It uses a mechanism called list comprehension. I have skipped the part for odd numbers, to simplify it. This approach first creates a new list, and then assigns it to the same variable.

Note it is generally not a good idea to modify a list while iterating it (adding and removing items).

Mirronelli
  • 740
  • 5
  • 14
0

You should not modify a list while iterating on it, this always causes problems ;)


You'd better iterate over it using it's indices, and replace the value directly

for i in range(len(ls)):
    if ls[i] > 9:
        ls[i] -= 9

Or use a list comprehension to create a new list from ls:

ls = [i-9 if i>9 else i for i in ls]
azro
  • 53,056
  • 7
  • 34
  • 70
0

There are better answers above (@Mirronelli for instance), but I tried to keep this answer as close as possible to your original code, in case you needed to keep a similar structure.

ls = [1, 2, 3, 4 ,5, 6, 7, 8, 9]
odd_num = []
for element in ls:
    # Separate list into odd and even numbers
    if element % 2 != 0:
        # Create your odd list
        odd_num.append(element)
        ls.remove(element)

# You don't need to do append here
# Just use a list comprehension
odd_num = [element * 2 for element in odd_num]

# Again, you don't need append/remove here
# Just use a list comprehension
ls = [element for element in ls if element < 9]

print(ls)
JS4137
  • 314
  • 2
  • 11