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"]