How to remove multiple elements with remove function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to remove multiple elements with remove function?

Remove maxs and mins & print the rest. Is there a way without using a & b and without repeating the same structure twice? data = [1, 5, 7, 0.4, 0.4, 9, 9] a = min(data) while a in data: data.remove(a) b = max(data) while b in data: data.remove(b) print(data) #so... while min(data) in data: data.remove(min(data)) #doesn't work, which I expected while min(data) in data: data.remove(min(data)) break #only removes the first of duplicates a = min(data) while a in data: data.remove(a) #works, but could you do it just with functions? Something like: remove the minimum, also until there is a minimum equal to this minimium, remove it, then stop searching for the new minimum 2nd Q: Can you remove different elements using one remove function (remove.data(1,5) or remove.data[1,5] didn't work, I guess the remove function is not meant for that (I'm not yet familiar with del function). Before moving on through lessons I just want to clear some things up)).

7th Nov 2021, 9:24 AM
Jona Žonta
Jona Žonta - avatar
6 Answers
+ 3
No worries buddy. I misunderstood, thanks for feedback. kudos to Slick
7th Nov 2021, 10:52 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Jona Žonta data = [1, 5, 7, 0.4, 0.4, 9, 9] data.remove(min(data)) data.remove(max(data)) print(data)
7th Nov 2021, 10:19 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Cool, that code should work. And yeah, make that code into a function with a integer list parameter. Then you can supply any list of numbers. Thats what you do if you wanna use a peice of code multiple times. You make a function out of it, generalize the code, and use it wherever needed Edit: and oh yeah Jona Žonta , i only used ''.join() because i was working with a string and .join() makes output look better. Not really a use with a list of numbers
7th Nov 2021, 10:36 AM
Slick
Slick - avatar
+ 1
Slick #Thanks, from your code I figured this works: for i in range (data.count(min(data))): data.remove(min(data)) for i in range (data.count(max(data))): data.remove(max(data)) print(data) #Is there a way to join this two structures into one? To be honest, I didn't understand why print(''.join(sent)). Should I necessarily add something like "char" (or "a" in the example above) into code?
7th Nov 2021, 10:33 AM
Jona Žonta
Jona Žonta - avatar
+ 1
Rik Wittkopp This gives [1, 5, 7, 0.4, 9], but I wanted [1, 5, 7].
7th Nov 2021, 10:37 AM
Jona Žonta
Jona Žonta - avatar