Prot2014
Prot2014

Reputation: 95

python remove element from list without changing index of other elements

I have a list L = [a,a,b,b,c,c] now I want to remove first 'b' so that the L becomes [a,a,b,c,c]. In the new L the index of first 'c' is 3. Is there any way I can remove first 'b' from L and still get the index of first 'c' as 4. Thanks in advance.

Upvotes: 5

Views: 9593

Answers (2)

Akavall
Akavall

Reputation: 86178

Perhaps you can get your desired effect with pandas:

>>> import pandas as pd
>>> L = ['a','a','b','b','c','c']
>>> df = pd.DataFrame(L)
>>> df
   0
0  a
1  a
2  b
3  b
4  c
5  c

[6 rows x 1 columns]
>>> df = df.drop(3)
>>> df
   0
0  a
1  a
2  b
4  c
5  c

[5 rows x 1 columns]
>>> df.loc[4]
0    c
Name: 4, dtype: object
>>> df.loc[5]
0    c
Name: 5, dtype: object

Upvotes: 1

Duke
Duke

Reputation: 369

It isn't possible to completely remove an element while retaining the indices of the other elements, as in your example. The indices of the elements represent their positions in the list. If you have a list [a, a, b, b, c, c] and you remove the first b to get [a, a, b, c, c] then the indices adjust because they represent the positions of the elements in the list, which have changed with the removal of an element.

However, depending on what your use case is, there are ways you can get the behavior you want by using a different data structure. For example, you could use a dictionary of integers to objects (whatever objects you need in the list). For example, the original list could be represented instead as {0: a, 1: a, 2: b, 3: b, 4: c, 5: c}. If you remove the b at 'index' (rather, with a key of) 2, you will get {0: a, 1: a, 3: b, 4: c, 5: c}, which seems to be the behavior you are looking for.

Upvotes: 2

Related Questions