添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

I am looking for help. why the following code cannot show the result: [ 6, 9], instead it shows [ 2, 9].

my_list = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]
new_list =

for i in my_list:
if my_list.count(i) == 1:
distinct = my_list[i]
new_list.append(distinct)
else:
continue

print(“The list with unique elements only:”)
print(new_list)

Please when you’re posting code here can you try to format it correctly? There’s a code button in the toolbar at the top of the edit window or you can put triple backticks round the code.

i is a bad choice for a variable name in a for loop. It is too easy to get confused between whether you are using the values from the list (which is what you are using here) or the index of the loop element (which is how you used it). Much better to use a meaningful name for what it represents or if you can’t think of anything at least use a name such as value :

for value in my_list:

If you use a more descriptive name you’re much more likely to spot that distinct = my_list[value] isn’t what you want. You already have the value so don’t need to pull it out of the list there, just use it with:

new_list.append(value)
              

You’re assigning each of the numbers to i, but then doing my_list[i], which will give you the i’th element of my_list.

With clearer variable name, it’s doing this:

for number in my_list:
    if my_list.count(number) == 1:
        distinct = my_list[number] # <-- The element at the index given by number!
        new_list.append(distinct)