leota
leota

Reputation: 1756

Delete specific elements from a list in python

I have a list containing some countries and relative capitals. I would like to delete only the capitals to create a new countryList[] and viceversa. Here's my list

countryCapitalList= ['AFGHANISTAN=', 'KABUL', 'ALASKA=', 'JUNEAU', 'ALBANIA=', 'TIRANA', 'ALGERIA=', 'ALGERI']

As the countries correspond to an even number I was trying this way:

    i = 0

    for x in countryCapitalList[:]:
        del countryCapitalList[i]
        i = i + 1



    print countryCapitalList

but I get this error:

del countryCapitalList[i]
IndexError: list assignment index out of range

I really don't understand why. Can someone help me please?

Upvotes: 1

Views: 501

Answers (3)

user1462309
user1462309

Reputation: 489

If all your country entries have "=" in them, and nothing else does, the cleanest way is

countryCapitalList = [x for x in countryCapitalList if "=" not in x]

This is using list comprehensions. It goes through the list, selecting only those entries that do not have "=" in them.

Upvotes: 0

pcoving
pcoving

Reputation: 2788

The exception you're getting is because you're deleting by index, rather than by value. The list is getting shorter during the iteration and therefore the index is no longer meaningful. Instead, I would delete by value,

for x in countryCapitalList[:]:
     if isCapital(x):
          countryCapitalList.remove(x)

Upvotes: 1

zhangxaochen
zhangxaochen

Reputation: 34047

for this specific case, just delete elements with odd index:

In [1452]: countryList=countryCapitalList[:]

In [1453]: del countryList[1::2]

In [1454]: countryList
Out[1454]: ['AFGHANISTAN=', 'ALASKA=', 'ALBANIA=', 'ALGERIA=']

Upvotes: 2

Related Questions