我正在尝试从列表中删除一个元素,但只能使用range函数和append方法(作业问题)。当索引元素位置不等于position参数时,我的“ for循环”工作正常。但是我似乎无法使我的if语句正常工作到所需的输出。任何帮助将不胜感激。
这是我的代码:
def length(my_list):
result = 0
for char in my_list:
result += 1
return result
def remove(my_list,position):
new_list2 = [] # Create a new list
length2 = length(my_list) # Calls upon the length function
if position < 0:
new_list2.append(my_list[position])
for r in range(length2):
if r != position:
new_list2.append(my_list[r])
if position > length2:
(my_list)
return new_list2
str_list5 = ['f','i','r','e']
new_list = remove(str_list5,2)
print(new_list)
new_list = remove(str_list5,-1)
print(new_list)
new_list = remove(str_list5,10)
print(new_list)
我在-1和10位置的输出应该是:
['i','e']
['f','r']