5

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.

7
  • remove b insert some character. Commented Nov 20, 2014 at 5:27
  • 2
    No. You can't do that. Indexing is automatic. Commented Nov 20, 2014 at 5:29
  • 2
    If you did that, what would you expect to get from L[2] and L[3]? Commented Nov 20, 2014 at 5:30
  • idk y you want do do that??? Commented Nov 20, 2014 at 5:31
  • 1
    Do you want a dict instead? Also, removing items near the beginning of a list is costly, if you intend to do that frequently. Commented Nov 20, 2014 at 5:38

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, dict indeed is an option but I was looking a way to achieve this via list only. pandas approach below looks cool.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.