I am trying to get the following output from 4 different lists, I need to call an address_machine method and zip the items form the list and use a for loop to iterate over the new list then print them on a new line --> EXPECTED OUTPUT below:
["T Cruise","D Francis","C White"]
["2 West St","65 Deadend Cls","15 Magdalen Rd"]
["Canterbury", "Reading", "Oxford"]
["CT8 23RD", "RG4 1FG", "OX4 3AS"]
My method looks like this:
def address_machine(name, street_address, town, postcode):
address = "{0},{1},{2},{3}".format(name, street_address, town, postcode)
return address
print([address_machine(name, street_address, town, postcode) for name, street_address, town, postcode in
zip(["T Cruise", "D Francis", "C White"], ["2 West St", "65 Deadend Cls", "15 Magdalen Rd"],
["Canterbury", "Reading", "Oxford"], ["CT8 23RD", "RG4 1FG", "OX4 3AS"])])
This is posing a problem as the output I get looks like this and its all on one line:
['T Cruise,2 West St,Canterbury,CT8 23RD', 'D Francis,65 Deadend Cls,Reading,RG4 1FG', 'C White,15 Magdalen Rd,Oxford,OX4 3AS']
How do I need to write this Python adress_machine function to get the expected output?
You could use normal for
-loop
for name, street_address, town, postcode in zip(["T Cruise", "D Francis", "C White"], ["2 West St", "65 Deadend Cls", "15 Magdalen Rd"],
["Canterbury", "Reading", "Oxford"], ["CT8 23RD", "RG4 1FG", "OX4 3AS"]):
print([name, street_address, town, postcode])
or first create list with all elements and later for
-loop to display it
data = [[name, street_address, town, postcode] for name, street_address, town, postcode in zip(["T Cruise", "D Francis", "C White"], ["2 West St", "65 Deadend Cls", "15 Magdalen Rd"],
["Canterbury", "Reading", "Oxford"], ["CT8 23RD", "RG4 1FG", "OX4 3AS"])]
for item in data:
print(item)
And don't understand why you use function address_machine()
which convert list to string if you expecte result with lists.