Skip to content Skip to sidebar Skip to footer

How To Concatenate Tuples

I have this code: def make_service(service_data, service_code): routes = () curr_route = () direct = () first = service_data[0] curr_dir = str(first[1]) f

Solution 1:

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!

Solution 2:

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:

defmake_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.

Post a Comment for "How To Concatenate Tuples"