0

I want to delete each city from the list if the number of the characters is 5 or less.

cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai"]
j = 0
for i in cities:
    if len(i) <= 5:
        del cities[j]
    j += 1

That deletes only the first city which is 5 characters or less. But not the second one.

I also tried this:

i = 0
while i < len(cities):
    if len(cities[i]) <= 5:
        del cities[i]
    i += 1

but it gave me the same result!!

UPDATE: The easiest way to do it is just to add a slice:

for i in cities[:]:
        if len(i) <= 5:
            cities.remove(i)       

# output: ["New York", "Shanghai", "Munich"]

1 Answers1

2

What you're describing is known as a Filter operation. You should look at the docs. The following code uses it to generate a brand new list of city names in a single line of code. Constructing a new list will prevent you from a whole class of mistakes that you can make while mutating your memory. The wiki article on Referential Transparency is a good starting point.

cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai"]

citiesWithLongNames = filter (lambda cityName: len (cityName) > 5, cities)

print (citiesWithLongNames) # => ['New York', 'Shanghai', 'Munich']

You should also read up on all the built in functions, and you'll find that there is a bunch of stuff built into python already that keeps you from having to implement trivialities manually.


Bonus: Using List Comprehensions:

print ([city for city in cities if len (city) > 5])

Much cleaner than nested loops. :)

Prajjwal
  • 1,055
  • 2
  • 10
  • 17