Reputation: 11
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
i want to remove color [0,4,5] so the output will be :
color ['green', 'White', 'Black']
what should I write?
Upvotes: 0
Views: 105
Reputation: 102
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
inc =[0,4,5]
fil=list(set(color)-set([color[x] for x in inc ]))
print(fil)
Upvotes: -1
Reputation: 26211
Note: This is essentially the same answer as @Aplet123, but with a few additional details.
[v for i, v in enumerate(colors) if i not in {0, 4, 5}]
def drop(lst, to_drop):
drop_idx = frozenset(to_drop)
return [v for i, v in enumerate(lst) if i not in drop_idx]
colors = list(np.random.uniform(size=1_000_000))
to_drop = list(np.random.choice(np.arange(len(colors)), replace=False, size=10_000))
%timeit drop(colors, to_drop)
# 68.4 ms ± 233 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Upvotes: 0
Reputation: 752
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
list(map(color.pop, reversed([0, 4, 5])))
print(color)
['Green', 'White', 'Black']
Upvotes: 0
Reputation: 3731
Shortest code for your goal. The print statements are to show it works.
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
remove = [0,4,5]
remove.reverse()
for x in remove:
print(x)
color.pop(x)
print(color)
If the numbers in the removal list is changed (e.g. [0,5,4]) you can sort first:
remove.sort(reverse=True)
[color.pop(x) for x in remove]
Upvotes: 0
Reputation: 330
You'll have to subtract the position of the element you want to remove since every time you remove an element the length of the list is reduced giving other elements to the given positions,
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
color.pop(0)
color.pop(4-1)
color.pop(5-2)
print(color)
Upvotes: 0
Reputation: 35512
You can use a list comprehension along with enumerate
:
colors = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
indices = [0, 4, 5]
indices_set = set(indices)
filtered = [color for i, color in enumerate(colors) if i not in indices_set]
print(filtered) # ['Green', 'White', 'Black']
Upvotes: 2