Remove values from python list without changing indexs - python-3.x

I want to remove a values from python list without changing the index.
For example, if list is [20,30,40] , if I want remove the 20 from the list.
that list index become 30-0 and 40-1.but I need 30-1 and 40-2.
Is there any solution to my problem??

You need to use dictionaries:
assoc = { 0:20, 1:30, 2:40}
print( assoc[2] )
del assoc[1]
print( assoc[2] )
print(assoc)
Running this gives:
40
40
{0: 20, 2: 40}

Related

Python nested list conditional delete

I have a list of lists where some lists are not complete. I.e.:
data = [
['id1',1],
['id2'],
['id3'],
['id4'],
['id5',1]
]
I want to create a new list that contains only "full" lists.
Desired output:
[
['id1',1],
['id5',1]
]
I have tried:
new_data = [i for i in data if i[1]]
However, this returned:
List index error: Index out of range
I find it odd because the if[1] is right there.
Question
Is there a simple fix for a one-line approach, or must we use a for loop?
Instead of trying accessing the values, check for length:
new_data = [i for i in data if len(i) == 2]

can't remove some duplicate elements from a list in python

well I was trying to remove duplicate items from a list so it has unique items and I also wanted to use for and if my code went so well but in one condition I faced something I don't understand. this is the example :
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a:
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
print(a)
[1, 21, 21, 16, 20, 7]
I don't understand why !! It removes 2,3,28 which was predicted but not 21 !
any help would be great , thanks.
The best solution for this case is using set(). If you do list(set(a)) it will remove all duplicates.
Notice that set() is not the same as list() so be sure to turn it back to a list if you want to keep using list methods.
About your code, the problem with your code is that you're running on the list as you're changing it.
While you run over the items the indexes changes and that's why you miss some of the items.
You can see more clearly what happens if you add a print to understand what's x's value:
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a:
print(x)
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
I believe your issue is that you are changing the list while you're looping over it
Try using a.copy() to create a new copy of the list to loop over like so.
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a.copy():
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
print(a)
This code will output
[1, 16, 20, 7]

Delete sub-list from list in python

I need to remove the sub lists from a list in Python.
For example: The main list A contains
A=[ 'a,b,c', 'd,e,f' , 'g,h,i' , 'g,l,m' , 's,l,k' , 'd,k,l', 'a,g,d' ]
I need to remove the sub lists from A which begin with the items in the following list:
B = ['g','d']
so that Final List A = [ 'a,b,c', 's,l,k' , 'a,g,d' ]
Thanks in advance
Using list comprehension:
print([x for x in A if x[0] not in ['g', 'd']])
You can do it using list comprehension and split(",").
print([e for e in A if e.split(",")[0] not in B])
Output
['a,b,c', 's,l,k', 'a,g,d']
Your output above for your approach is wrong.
2nd Element 'd,e,f' should also be removed as start element 'd' is in second list.

Cumulatively add values to python dictionary

Suppose ,I have a dictionary
key={'a':5}
Now ,I want to add values to it cumulatively without overwriting the current value but adding on to it.How to do it?
I am giving an instance:
for post in doc['post']:
if 'wow' in post:
value=2
for reactor in post['wow']['reactors']:
dict_of_reactor_ids.update({reactor['img_id']:value})
if 'sad' in post:
value=2
for reactor in post['sad']['reactors']:
dict_of_reactor_ids.update({reactor['img_id']:value})
Suppose if the dictionary is like this in first iteration
dict_of_reactor_ids={101:2,102:1}
and NOW I want to increase the value of 101 key by 3 ,then how to do that.
dict_of_reactor_ids={101:5,102:1}
Now in second iteration of post ,I want to add values to the current values in dictionary without overwriting the current value.
I have tried update method but I think it just updates the whole value instead of adding onto it.
Sounds like a typical case of Counter:
>>> from collections import Counter
>>> c = Counter()
>>> c["a"] += 1 # works even though "a" is not yet present
>>> c.update({"a": 2, "b": 2}) # possible to do multiple updates
{"a": 3, "b": 2}
In your case the benefit is that it works even when the key is not already in there (default value is 0), and it allows updates of multiple values at once, whereas update on a normal dict would overwrite the value as you've noticed.
You can also use defaultdict, it "defaults" when there is not yet an existing key-value pair and you still use the cumulative add +=:
from collections import defaultdict
dict_of_reactor_ids = defaultdict(int)
dict_of_reactor_ids[101] += 2
dict_of_reactor_ids[102] += 1
dict_of_reactor_ids['101'] += 3
print(dict_of_reactor_ids['101'])
5

Indexing the list in python

record=['MAT', '90', '62', 'ENG', '92','88']
course='MAT'
suppose i want to get the marks for MAT or ENG what do i do? I just know how to find the index of the course which is new[4:10].index(course). Idk how to get the marks.
Try this:
i = record.index('MAT')
grades = record[i+1:i+3]
In this case i is the index/position of the 'MAT' or whichever course, and grades are the items in a slice comprising the two slots after the course name.
You could also put it in a function:
def get_grades(course):
i = record.index(course)
return record[i+1:i+3]
Then you can just pass in the course name and get back the grades.
>>> get_grades('ENG')
['92', '88']
>>> get_grades('MAT')
['90', '62']
>>>
Edit
If you want to get a string of the two grades together instead of a list with the individual values you can modify the function as follows:
def get_grades(course):
i = record.index(course)
return ' '.join("'{}'".format(g) for g in record[i+1:i+3])
You can use index function ( see this https://stackoverflow.com/a/176921/) and later get next indexes, but I think you should use a dictionary.

Resources