Reputation: 33
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')
Upvotes: 1
Views: 8293
Reputation: 121
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!
Upvotes: 2
Reputation: 7293
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.
Upvotes: 1