I have a list as below:
device = [('nvme2n1',),
('nvme1n1', '/local'),
('nvme0n1',),
('nvme0n1p1', '/'),
('nvme0n1p128',),
('nvme3n1',)]
I want to delete few tuples from this list containing nvme1n1
or nvme0n1p1
or nvme0n1p128
or nvme0n1
.
so the final list will have
final_device = [('nvme2n1',),('nvme3n1',)]
tried as below but didn't work & got error "AttributeError: 'tuple' object has no attribute 'startswith'"
for word in devices[:]:
if word.startswith("nvme0n1","nvme0n1p1","nvme0n1p128"):
devices.remove(word)
Can anyone help with this?
Use the del statement to remove a tuple from a list of tuples, e.g. del list_of_tuples[0] . The del statement can be used to remove a tuple from a list by its index, and can also be used to remove slices from a list of tuples.
To remove the first element from a tuple in Python, slice the original tuple from the second element (element at index 1) to the end of the tuple. This will result in a new tuple with the first element removed.
To explicitly remove an entire tuple, just use the del statement.
Remove duplicates from a tuple using a set You can use a set to remove duplicates from a tuple in Python. First, create a set of unique elements from the tuple using the set() function and then use the tuple() function to create a new tuple from the resulting set.
devices = [('nvme2n1',), ('nvme1n1', '/local'),
('nvme0n1',), ('nvme0n1p1', '/'),
('nvme0n1p128',), ('nvme3n1',)]
devices = [device for device in devices if device[0] not in
(("nvme0n1", "nvme0n1p1", "nvme0n1p128", "nvme0n1"))]
print(devices)
output
[('nvme2n1',), ('nvme1n1', '/local'), ('nvme3n1',)]
@JamesTollefson in their answer address the particular problem in your code and how to remedy it. This is just different and in my opinion better/cleaner way to achieve what you want.
You can even use a list comprehension to make it simpler.
As James mentioned in his answer, you need to do word[0]
as word
is a tuple and not a string.
startswith
can take a tuple to check with.
[dev for dev in devices if not dev[0].startswith(("nvme0n1","nvme0n1p1","nvme0n1p128"))]
But if you're looking for exact matches, you can do,
[dev for dev in devices if dev[0] not in ("nvme0n1","nvme0n1p1","nvme0n1p128")]
The word
s you are iterating through in the devices
list are tuples. You need to access that part of that tuple you are interested in as follows:
for word in devices[:]:
if word[0] in ["nvme0n1","nvme0n1p1","nvme0n1p128"]:
devices.remove(word)
@JamesTollefson's answer is nice and gets to the heart of the matter.
As a side note, just wanted to add that when dealing with lists and dicts, you can make your code more concise and elegant using list comprehensions:
devices = [d in devices if d[0] not in {"nvme0n1", "nvme0n1p1", "nvme0n1p128", "nvme0n1"}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With