remove items from specific place on the list - python

I want to remove some items from specific places. for example, I have list [a,b,c,d,e,f,g,h,i]. the number of items in this list constantly changes.
That is why I need special method that is helps to remove items from same place. Now the modified list should be like that: list [a,b,c,d,e,f,i]. g and h should always be removed.

Do you want to remove the second- and third-last item from the list?
This can be achieved like this:
del lst[-3:-1]

If you create dictionaries with necessary indexes you can use them to create a new list.
lst = ['a','b','c','d','e','f','g','h','i']
other = ['a','y','b','c','d','e','g','h','l']
indexed_lst = {i: item for i, item in enumerate(lst)}
indexed_other = {i: item for i, item in enumerate(other)}
[item for i, item in indexed_lst.items() if indexed_lst.get(i, None) != indexed_other.get(i, None) ]

You can remove from the list either by index or by value. In either case it is a good practice to check if the index/value is present in the list. As for removing an item from the list you could use one of the below based on what info is available / output required.
Remove an item by index and get its value: pop()
# where i is the index of the value to be removed
if i < len(lst)
result = l.pop(i)
Remove items by index or slice: del()
# where i is the index of the value to be removed
if i < len(lst) :
lst.del(i)
Remove an item by value: remove()
# where `h` is the value to be removed
if 'h' in lst:
lst.remove('h')
You could also remove items from a list based on a given condition, in which case you could use list comprehensions
l = list(range(10))
# Remove all the odd numbers
print([i for i in l if i % 2 != 0])

ahh i understand your answer, if you use index like this
Remove items by index, specific place
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for index,item in enumerate(lst) if index != 6 and index != 7]
print(lst)
or Remove items by Value
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)

Use the .pop() to pop off any given index off the list

lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
if you have more input, tell me

Related

Finding item(s) in python list where it is not grouped with similar values

I'm trying get a list (using Python) of indexes for items in a list that are not grouped with similar values.
For example, given the list [1,1,0,0,1,1,0,0] items at index 4,5,6,7 are errors because they're not grouped with the the first set of similar values. The first time an item or similar groups of items is seen in a list is considered the correct position, so order isn't really important. Ideally, I'd be returned a list of indexes like [4,5,6,7]
Could you please check if this works for you?
input_list=[1,1,0,0,1,1,0,0]
dict1={} #dictionary to store the values
return_list=[]
for i,v in enumerate(input_list):
x=dict1.get(v)
if(x!=None and x!=i-1):
return_list.append(i)
else:
dict1[v]=i
print(return_list)
def get_incorrect_indecies(numbers):
from itertools import groupby
seen_keys = set()
for key, group in groupby(enumerate(numbers), key=lambda tpl: tpl[1]):
if key in seen_keys:
for element in group:
yield element[0]
else:
seen_keys.add(key)
numbers = [1, 1, 0, 0, 1, 1, 0, 0]
print(list(get_incorrect_indecies(numbers)))
Output:
[4, 5, 6, 7]
>>>
What about something like this?
def checkgrouped(List: list) -> list:
usedvalues = [] # stored the values already used
badindexes = [] # stores the indexes of invalid items
for i in range(len(List)): # Iterating over the range instead of the list itself to make it easier to check adjacent items and get indexes
if List[i] in usedvalues: # Check if item was already stored in used values
badindexes.append(i) # Append index of item to bad indexes if item is invalid
elif List[i] != List[i + 1]: # Check if item is not different to the next item
usedvalues.append(List[i]) # Append item to the list of used values
return badindexes
Here is how:
def check(lst):
d = []
for i,v in enumerate(lst):
if v not in d or d[-1] == v:
d.append(v)
else:
return [q for q in range(i,len(lst))]
print(check([1,1,0,0,1,1,0,0]))
Output:
[4, 5, 6, 7]

how to extract from list python, element with index multiple of 2

I just want to get those with the index that is a multiple of two
code=[1,2,4,7,2,6,8]
ncode=[code[i] for i%2==0]
Just use this indexing method:
code[::2]
If you want the odd index
code[1::2]
Generally, this is how it works:
seq = L[start:stop:step]
seq = L[::2] # get every other item, starting with the first
seq = L[1::2] # get every other item, starting with the second
You can use list comprehensions this way :
code=[1,2,4,7,2,6,8]
print [val for i,val in enumerate(code) if i%2==0]
enumerate() returns the index and value at the index, which is stored in i and value respectively.
For more details:
list comprehension
enumerate
code = [1,2,4,7,2,6,8]
new_code = []
for i in range(0, len(code), 2): ### iterate over even indexes
new_code.append(code[i])
print new_code

Add item into array if not already in array

How can I insert item into the array if its not already there?
This is what I tried:
[..]
k = []
for item in myarray:
if not item in k:
print("Item is in array already.")
k[] = item
Your code has the right idea but just use k.append(item) instead of k[] = item.
Also it is cleaner to say if item not in k:
k[] = item is invalid syntax. All you need to do is just remove that line and use list.append()
for item in myarray:
if not item in k:
print("Item is in array already.")
k.append(item)
list.append() adds an item to the end of the list.
If you don't care about the order of the items in the list, you can convert it to a set to filter out any duplicates.
k = list(set(myarray))
Or if k already contains something...
k = [...] # optionally non-empty array
k = list(set(k) | set(myarray))
What that does is convert both myarray and k into sets, and combines them so that the result is a unique list that containing the contents of both k and myarray.

deleting multiple elements without updating till the end

I have two lists:
list_a = [1,5,8]
list_b = [12,4,2,5,7,5,3,6,8]
The elements in list_a correspond to the indices of elements in list_b. Both lists are of size greater than 100.
How can I delete the elements of list_b whose indices are in list_a,
so if you take the lists above the resulting list is [12,2,5,7,3,6]?
Two options:
Create a new list with a list comprehension:
newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete]
This will be all the faster if indices_to_delete was a set:
indices_to_delete = set(indices_to_delete)
newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete]
because membership testing in a set is O(1) vs. O(n) in a list.
Remove the indices in reverse-sorted order from the list in-place:
for index in sorted(indices_to_delete, reversed=True):
del oldlist[index]
If you don't remove items in reverse sorted order, items with higher indices are moved up as items with lower indices are removed and the rest of your indices_to_delete no longer match the items you needed to remove.
This should accomplish that:
for delidx in reversed(toDelete):
del otherList[delidx]
Also, using a list comprehension:
l2 = [elem for i, elem in enumerate(l1) if i not in toDelete]
now that I understand the question
a = numpy.array(list2)
mask = [True]*len(a)
mask[list1] = False
print a[mask]
Ok, this a slightly over-engineered solution, but here it is
def get_newl(li, index):
index = sorted(index, reverse=True)
i=0
while i < (len(li)-len(index)):
x = index.pop()
while i < x:
yield li[i]
i+=1
i+=1
Run the code here http://codebunk.com/bunk#-Isxeb4TZOHBCvQi4EsY

python modify item in list, save back in list

I have a hunch that I need to access an item in a list (of strings), modify that item (as a string), and put it back in the list in the same index
I'm having difficulty getting an item back into the same index
for item in list:
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[item] = item
print item
now I get an error
TypeError: list indices must be integers, not str
due to this line list[item] = item
which makes sense! but I do not know how to put the item back into the list at that same index using python
what is the syntax for this? Ideally the for loop can keep track of the index I am currently at
You could do this:
for idx, item in enumerate(list):
if 'foo' in item:
item = replace_all(...)
list[idx] = item
You need to use the enumerate function: python docs
for place, item in enumerate(list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.
Since you had problems with enumerate, an alternative from the itertools library:
for place, item in itertools.zip(itertools.count(0), list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
A common idiom to change every element of a list looks like this:
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
This can be rewritten using enumerate() as:
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
See enumerate.
For Python 3:
ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
ListOfStrings[idx] = "bar"

Categories

Resources