Python list subtraction operation

Use a list comprehension: [item for item in x if item not in y] If you want to use the – infix syntax, you can just do: class MyList(list): def __init__(self, *args): super(MyList, self).__init__(args) def __sub__(self, other): return self.__class__(*[item for item in self if item not in other]) you can then use it like: x … Read more

Transpose list of lists

Python 3: # short circuits at shortest nested list if table is jagged: list(map(list, zip(*l))) # discards no data if jagged and fills short nested lists with None list(map(list, itertools.zip_longest(*l, fillvalue=None))) Python 2: map(list, zip(*l)) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Explanation: There are two things we need to know to understand … Read more

How to delete an item in a list if it exists?

1) Almost-English style: Test for presence using the in operator, then apply the remove method. if thing in some_list: some_list.remove(thing) The removemethod will remove only the first occurrence of thing, in order to remove all occurrences you can use while instead of if. while thing in some_list: some_list.remove(thing) Simple enough, probably my choice.for small lists … Read more

How can I remove an element from a list?

If you don’t want to modify the list in-place (e.g. for passing the list with an element removed to a function), you can use indexing: negative indices mean “don’t include this element”. x <- list(“a”, “b”, “c”, “d”, “e”); # example list x[-2]; # without 2nd element x[-c(2, 3)]; # without 2nd and 3rd Also, … Read more

Splitting on last delimiter in Python string?

Use .rsplit() or .rpartition() instead: s.rsplit(‘,’, 1) s.rpartition(‘,’) str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case. Demo: >>> s = “a,b,c,d” >>> s.rsplit(‘,’, 1) [‘a,b,c’, ‘d’] >>> s.rsplit(‘,’, 2) … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)