1

If I have the following data type:

[('a', 'digital-text'), ('b', 'bbbbbbb'), ('c', '1318913293'), ('d', '1-3')]

How to I remove item b so the output will look like:

[('a', 'digital-text'), ('c', '1318913293'), ('d', '1-3')]

How do I also check if b exists before deleting it? I tried if 'b' in xxxx but this can't find it

I am new to Python

Jsd
  • 11
  • 2

4 Answers4

7

You could use a list comprehension like this:

something = [(key, value) for key, value in something if key != 'b']

However, it looks like you're trying to reinvent a dictionary for some reason. If it doesn't have to be ordered, just use a dictionary:

something = {
    'a': 'digital-text',
    'b': 'bbbbbbb',
    'c': '1318913293',
    'd': '1-3',
}
del something['b']

If it does need to be ordered, you can use collections.OrderedDict rather than dict:

from collections import OrderedDict
something = OrderedDict([
    ('a', 'digital-text'),
    ('b', 'bbbbbbb'),
    ('c', '1318913293'),
    ('d', '1-3')
])
del something['b']

With a dictionary, if you need it back in the format you have in your question, just call items() on the dictionary.

>>> # assuming something is an OrderedDict and you've already deleted the item
>>> # if it was a plain dict, it might be in a different order
>>> # if you haven't deleted the item, it would still be there
>>> something.items()
[('a', 'digital-text'), ('c', '1318913293'), ('d', '1-3')]

Additionally, to convert a list like in your question into some kind of dictionary, just pass it into it:

>>> dict([
...     ('a', 'digital-text'),
...     ('b', 'bbbbbbb'),
...     ('c', '1318913293'),
...     ('d', '1-3')
... ])
{'a': 'digital-text', 'b': 'bbbbbbb', 'c': '1318913293', 'd': '1-3'}
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • If only one item is to be deleted, you can also avoid looking at items after the one you delete in the list by using a normal loop: `for for index, (key, value) in enumerate(the_list): if key == 'b': del the_list[index]; break` – agf Oct 18 '11 at 19:16
0

A list comprehension does this nicely:

new_list = [element for element in old_list if element[0] != "b"]
oadams
  • 3,019
  • 6
  • 30
  • 53
0

For removal you can do:

my_list = [('a', 'digital-text'), ('b', 'bbbbbbb'), ('c', '1318913293'), ('d', '1-3')]
my_list.remove(('b', 'bbbbbbb'))

or:

my_list = [('a', 'digital-text'), ('b', 'bbbbbbb'), ('c', '1318913293'), ('d', '1-3')]
del my_list[2]

If you wanna create a new list without that value you can use list comprehension:

my_list = [('a', 'digital-text'), ('b', 'bbbbbbb'), ('c', '1318913293'), ('d', '1-3')]
new_list = [(key, value) for key, value in my_list if key != 'b']
Nicola Coretti
  • 2,655
  • 2
  • 20
  • 22
0

Try to use "filter":

newList = filter(lambda (k, v): k != 'b', oldList)

In python 2 it will return filtered list, in python 3.x - iterator.

Renat
  • 417
  • 4
  • 12