Python Forum
# only print cities that names start "Q" or earlier - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: # only print cities that names start "Q" or earlier (/thread-4013.html)



# only print cities that names start "Q" or earlier - nikhilkumar - Jul-17-2017

my question here
print cities from visited_cities list in alphbetical order using .sort()
# only print cities that names start "Q" or earlier
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
visited_cities.sort()
print(visited_cities)
new_cities=[]
for cities in visited_cities:
    if cities[0]=="A"or"B"or"C"or"D"or"E"or"F"or"G"or"H"or"I"or"J"or"K"or"L"or"M"or"N"or"O"or"P"or"Q":
        new_cities.append(cities)
print(new_cities)
But I am getting following output:
['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar', 'Shanghai', 'São Paulo', 'Toyko']
['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar', 'Shanghai', 'São Paulo', 'Toyko']

But Desired output is:
['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar']


RE: # only print cities that names start "Q" or earlier - buran - Jul-17-2017

see http://python-forum.io/Thread-Multiple-expressions-with-or-keyword

also, have a look at str.startswith() method for better, more pythonic way of doing the same

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
new_cities = []
for city in visited_cities:
    if city.startswith(tuple('ABCDEFGHIJKLMNOPQ')):
        new_cities.append(city)
new_cities.sort()
print(new_cities)
or even better, using list comprehension

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
new_cities = [city for city in visited_cities if city.startswith(tuple('ABCDEFGHIJKLMNOPQ'))]
new_cities.sort()
print(new_cities)
in both cases, the output is
Output:
['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar']
Sort the subset - new_cities list, not the entire visited_cities list, because it is shorter one


RE: # only print cities that names start "Q" or earlier - buran - Jul-17-2017

you can use also

from string import ascii_uppercase

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
new_cities = [city for city in visited_cities if city.startswith(tuple(ascii_uppercase[:17]))]
new_cities.sort()
print(new_cities)



RE: # only print cities that names start "Q" or earlier - Larz60+ - Jul-17-2017

another method:

visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
print('visited_cities: {}'.format(visited_cities))
new_cities=[]

for city in visited_cities:
   if city[0] < 'R':
       new_cities.append(city)
new_cities.sort()
print('new_cities: {}'.format(new_cities))
results
Output:
visited_cities: ['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar', 'Shanghai', 'São Paulo', 'Toyko'] new_cities: ['Dubai', 'Hyderabad', 'Mexico City', 'Munich', 'New York', 'Qatar']



RE: # only print cities that names start "Q" or earlier - Barrowman - Jul-17-2017

This will also work:
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
visited_cities.sort()
new_cities=[]
for cities in visited_cities:
   if cities[0]<="Q":
       new_cities.append(cities)
print(new_cities)
As will :
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
for cities in visited_cities:
   if cities[0]<="Q":visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]
for cities in visited_cities:
    if cities[0]<="Q":
        print(cities)
       print(cities)



RE: # only print cities that names start "Q" or earlier - DeaD_EyE - Jul-17-2017

With a generator:

def get_till_included(iterable, start):
    found = False # set found condition to false
    for element in sorted(iterable):
        # iterates over a sorted list of strings
        # if no element fulfilled the condistion startswith, it will
        # yield the whole sorted list
        if not found:
            # yields the element if the start is not found at the beginning of the string
            yield element
            found = element.startswith(start) # look if the string starts with start
        elif found and element.startswith(start):
            # yields the element if already one was found which starts with start.
            yield element
        else:
            # stops the loop, when one element with the start was already found,
            # but the current element has not fulfilled the condition startswith
            break

# this list won't get modified
visited_cities = ["New York", "Shanghai", "Munich", "Toyko", "Dubai", "Mexico City", "São Paulo", "Hyderabad","Qatar"]

generator = get_till(visited_cities, 'M')
print('generator object', generator) # does nothing, values are lazy evaluated during iteration, the print function does not iterate over something

generator = get_till(visited_cities, 'M')
print('as list', list(generator)) # as list, which is mutable

generator = get_till(visited_cities, 'M')
print('as tuple', tuple(generator)) # as immutable sequence

generator = get_till(visited_cities, 'M')
print('as set', set(generator)) # only unique elements, no order
The benefit:
  • You don't mutate the original list.
  • The generator does not define the data type of the final result
  • You can iterate over the generator

Example to iterate over the generator:
for city in get_till(visited_cities, 'M'):
    print('City:', city)
With generators you can split tasks into smaller tasks and stick them together.