1

I have this code:

def make_service(service_data, service_code):
    routes = ()
    curr_route = ()
    direct = ()

    first = service_data[0]
    curr_dir = str(first[1])

    for entry in service_data:
        direction = str(entry[1])
        stop = entry[3]

        if direction == curr_dir:
            curr_route = curr_route + (stop, )
            print((curr_route))

When I print((curr_route)), it gives me this result:

('43009',)
('43189', '43619')
('42319', '28109')
('42319', '28109', '28189')
('03239', '03211')
('E0599', '03531')

How do I make it one tuple? i.e. ('43009','43189', '43619', '42319', '28109', '42319', '28109', '28189', '03239', '03211', 'E0599', '03531')

2 Answers2

2
tuples = (('hello',), ('these', 'are'), ('my', 'tuples!'))
sum(tuples, ())

gives ('hello', 'these', 'are', 'my', 'tuples!') in my version of Python (2.7.12). Truth is, I found your question while trying to find how this works, but hopefully it's useful to you!

Willbeing
  • 121
  • 3
  • if you wonder about the performance of this answer, go (here)[https://stackoverflow.com/questions/42059646/concatenate-tuples-using-sum]. Basically, it is OK for small tuples, but went there is a lot of tuples you would prefer to use itertools: `import itertools as it: tuple(it.chain.from_iterable(tuples))` – toto_tico Aug 31 '17 at 14:16
  • Also notice that if you want to iterate over the values, itertool returns an iterator and this could really make the difference as you won't have to iterate the elements twice: `for i in it.chain.from_iterable(tuples): print(i)` – toto_tico Aug 31 '17 at 14:18
1

Tuples exist to be immutable. If you want to append elements in a loop, create an empty list curr_route = [], append to it, and convert once the list is filled:

def make_service(service_data, service_code):
    curr_route = []
    first = service_data[0]
    curr_dir = str(first[1])

    for entry in service_data:
        direction = str(entry[1])
        stop = entry[3]

        if direction == curr_dir:
            curr_route.append(stop)

    # If you really want a tuple, convert afterwards:
    curr_route = tuple(curr_route)
    print(curr_route)

Notice that the print is outside of the for loop, which may be simply what you were asking for since it prints a single long tuple.

JulienD
  • 7,102
  • 9
  • 50
  • 84