-2
list = [500,400,30]
removing = list.remove(0)
shift_left = removing.extend('0')
print(shift_left)
Traceback (most recent call last):
  File "C:/code/python/week08/selflearn01.py", line 3, in <module>
    shift_left = removing.extend('0')
AttributeError: 'NoneType' object has no attribute 'extend'

Im trying to do a list of 3 numbers in it and the first number (index 0) need to move to the last number (to became index 2) for example: list = [500,400,30] and it supposed to print after everything [400,500,30]

chicken
  • 1
  • 1
  • `list.remove(0)` returns nothing – Ikram Khan Niazi Dec 29 '22 at 13:51
  • 2
    First, don't use the names of built-ins like `list` as variable names. It shadows the built-in and leads to all sorts of subtle bugs in larger programs. Second, `list.remove()` operates on the list in-place - it doesn't return a modified list. – MattDMo Dec 29 '22 at 13:51
  • can you help me do something else, or help me on which line should i change ? i changed list to my_list – chicken Dec 29 '22 at 13:56

3 Answers3

1

All those functions are in-place, remove the assignments. You should also use append rather than extend

lst = [0, 1, 2]
lst.remove(0)
lst.append(0)
print(lst) # [1, 2, 0]

Another way is to use slicing

lst = [0, 1, 2]
lst = lst[1:] + [lst[0]]
print(lst) # [1, 2, 0]
Guy
  • 46,488
  • 10
  • 44
  • 88
0

.remove() is in-place; it alters your list and does not return a list. It returns None and you are trying to call extend on None.

my_list = [0,1,2]
my_list.remove(0)
my_list.extend('0')
print(my_list)
tripleee
  • 175,061
  • 34
  • 275
  • 318
Chris
  • 476
  • 4
  • 10
0

Firstly, list is an inbuilt python function and it is bad practice to name variables the same as built in functions. I have renamed this to lst:

lst = [0,1,2]

.remove() is an inplace function, so running just lst.remove(0) and then checking the lst variable would output:

[1, 2]

However, you're setting lst = lst.remove(0). if you check lst after running this, you would see that lst is None (hence your error).

In the same way, extend is also an inplace function, so you don't need to assign it to a new variable. Instead just do lst.extend('0').

Full code:

lst = [0,1,2]
lst.remove(0)
lst.extend('0')
print(lst)

Output:

[1, 2, '0']

Note: you're adding 0 as a string (text) to your shifted list, rather than as an integer (number). If you want it as a number, change to lst.extend(0).

Emi OB
  • 2,814
  • 3
  • 13
  • 29