can't remove some duplicate elements from a list in python - python-3.x

well I was trying to remove duplicate items from a list so it has unique items and I also wanted to use for and if my code went so well but in one condition I faced something I don't understand. this is the example :
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a:
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
print(a)
[1, 21, 21, 16, 20, 7]
I don't understand why !! It removes 2,3,28 which was predicted but not 21 !
any help would be great , thanks.

The best solution for this case is using set(). If you do list(set(a)) it will remove all duplicates.
Notice that set() is not the same as list() so be sure to turn it back to a list if you want to keep using list methods.
About your code, the problem with your code is that you're running on the list as you're changing it.
While you run over the items the indexes changes and that's why you miss some of the items.
You can see more clearly what happens if you add a print to understand what's x's value:
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a:
print(x)
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)

I believe your issue is that you are changing the list while you're looping over it
Try using a.copy() to create a new copy of the list to loop over like so.
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a.copy():
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
print(a)
This code will output
[1, 16, 20, 7]

Related

Python doesn`t work right. Parent list is changing by changing hereditary list

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
for i in range(1, 27):
for j in range(1,27):
if j!=i:
lst = a
print(lst)
print(a)
lst.remove(i)
lst.remove(j)
print(lst)
print(a)
List 'a' is getting smaller coz i change list 'lst', wtf is this?
I just started to perform codewars kata.
By default, python creates a reference for an object. If you want to make an actual copy with new memory what you can do is:
from copy import deepcopy
lis_copy = deepcopy(lis)

Remove values from python list without changing indexs

I want to remove a values from python list without changing the index.
For example, if list is [20,30,40] , if I want remove the 20 from the list.
that list index become 30-0 and 40-1.but I need 30-1 and 40-2.
Is there any solution to my problem??
You need to use dictionaries:
assoc = { 0:20, 1:30, 2:40}
print( assoc[2] )
del assoc[1]
print( assoc[2] )
print(assoc)
Running this gives:
40
40
{0: 20, 2: 40}

Is it possible to run a command on every individual list item in the order they are placed?

I have a list in python with a random number of items. Is it possible to run the same command on every individual list item in order from 1st to last so that I can convert the output of the command into another list with different variables?
If this is possible than can I create a os.system() command for Mac OS X that runs the OS X afplay command for each individual item again in order from the new list?
Your first question sounds like something you can solve with list comprehensions https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
initial_list = [0, 9, 99, 999]
def increment(value):
"""Increment value by one."""
value += 1
return value
# This is a list comprehension, it is basically a for-loop
new_list = [increment(list_item) for list_item in initial_list]
print(f'Old list: {initial_list}')
print(f'New list: {new_list}')
Which produces:
Old list: [0, 9, 99, 999]
New list: [1, 10, 100, 1000]
For your second question, I don't have any experience with Mac OS X, but maybe you could try something like this? I hope this helps you figure it out!
import os
audio_files = ['/Media/Sound1.wav', '/Media/Sound2.wav', '/Media/Sound3.wav']
play = [os.system(f'afplay {audio_file}') for audio_file in audio_files]
play[0] # play the first audio file
# play all the files sequentially
for audio_file in play:
play[audio_file]
EDIT: Now that I read your question again, I think what you want is something like this?
import os
audio_files = ['/Media/Sound1.wav', '/Media/Sound2.wav', '/Media/Sound3.wav']
processed_audio_files = [do_something(audio_file) for audio_file in audio_files]
for audio_file in processed_audio_files:
os.system(f'afplay {audio_file}')

Deleting Dictionaries Keys with a For If Statement in Python 3

I feel very dumb asking this. How do I delete a keys in a dictionary with an if statement that references the values. When I do this:
newdict = {"a":1,"b":2,"c":3}
for (key,value) in newdict:
if value == 2:
del newdict[key]
print(newdict)
It throws this error:
line 3, in <module>
for (key,value) in newdict:
ValueError: not enough values to unpack (expected 2, got 1)
Thank you.
If you need to delete based on the items value, use the items() method or it'll give ValueError. But remember if you do so it'll give a RuntimeError. This happens because newdict.items() returns an iterator not a list. So, Convert newdict.items() to a list and it should work. Change a bit of above code like following -
for key,value in list(newdict.items()):
if value == 2:
del newdict[key]
output -
{'a': 1, 'c': 3}

Returning a list of N dictionary keys that have the maximum integer values

my_dict = {'label': 6, 'label_2': 5, 'label_3': 9, 'label_4': 12}
I would like to create a list that will contain the top 2 (or 3, or 4, or 50... this will vary) dictionary keys, according to their highest values. So in the example above if I wanted the top 2, I should get:
['label_3', 'label_4']
for top 3 I should get:
['label', 'label_3', 'label_4']
And so on.
After reading some other stackoverflow threads, I've been experimenting with heapq, but can't get it to work the way I want. Would appreciate some help.
Of course, the moment I post here, I find a solution (thanks to the heapq documentation). This works:
my_list = heapq.nlargest(3, my_dict, key=my_dict.get)
This will go over my_dict and return the keys with the 3 largest values.
Thanks.

Resources