Remove problem | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Remove problem

How to remove more than one item or different items at one time? For example: nums=[1,2,3,3,3,4,5,4] Can I remove all 3 or 2 and 4 in one line? And how to remove the second 4?

7th Feb 2017, 9:33 AM
C.R.Devila
C.R.Devila - avatar
7 Answers
+ 3
# if you are looking for a one liner try nums=[1,2,3,3,3,4,5,4] # filter out all duplicates from a list print(list(set(nums))) # or if you just want it as a set just go print(set(nums)) # remove specific numbers from a list # an example of removing all 3's and 4's print([x for x in nums if x not in [3,4]]) # or to alter by index position use slicing notation # remove the last position from the list print(nums[:-1])
7th Feb 2017, 11:38 AM
richard
+ 1
you have to iterate the list and remove the nodes you don't need with a condition, you can use a while or you can do it with a recursive method. Hope it helps :)
7th Feb 2017, 9:51 AM
Luciano Pumeda Ale
Luciano Pumeda Ale - avatar
+ 1
@Ladislav Milunovic What do you mean??
7th Feb 2017, 9:58 AM
C.R.Devila
C.R.Devila - avatar
+ 1
@Luciano Pumeda Ale Could you write me an example? Thank you so much: )
7th Feb 2017, 10:01 AM
C.R.Devila
C.R.Devila - avatar
+ 1
That way you just fill your [set()] list, you have to add the condition to erase the numbers you don't want
7th Feb 2017, 10:02 AM
Luciano Pumeda Ale
Luciano Pumeda Ale - avatar
0
mySet = set() for e in nums: mySet.add(e)
7th Feb 2017, 9:56 AM
Ladislav Milunović
Ladislav Milunović - avatar
0
I mean to create set. It is type that doesn't accept duplicates. if you have a list just iterate it and add items to set. or make set imideatelly if you dont want duplicates
7th Feb 2017, 10:05 AM
Ladislav Milunović
Ladislav Milunović - avatar