Python Forum
Is there a more efficient way to code this project? - 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: Is there a more efficient way to code this project? (/thread-13043.html)



Is there a more efficient way to code this project? - gkiranseo - Sep-25-2018

I'm learning Python programming from the Mindmajix training and I just completed classes about lists, tuples, functions and methods. One of the projects following this lecture is to create a program which takes in a list as an input and outputs a corresponding string, as the following example showcases:

Input: ['bikes', 'cars', 'buses', 'trucks']
Output: bikes, cars, buses, and trucks

So I wrote the code like the below source code:

def listToString(someList):
    for i in range(len(someList)):
        newString = str(someList[i])

        if i == (len(someList)-1):
            print('and ' + str(someList[i]))
        else:
            print(newString, end=', ')

someList = ['bikes','cars','buses','trucks']
listToString(someList)
I feel like I didn't use everything (for example, some methods) to solve the problem. Is there a more efficient way to code this project?


RE: Is there a more efficient way to code this project? - Larz60+ - Sep-25-2018

if python 3.6 or newer:
some_list = ['bikes','cars','buses','trucks']

def list_to_string(any_list):
    return f"{', '.join(map(str, any_list[:-1]))} and {any_list[-1]}"

print(list_to_string(some_list))
otherwise:
some_list = ['bikes','cars','buses','trucks']

def list_to_string(any_list):
    return "{} and {}".format(', '.join(map(str, any_list[:-1])), any_list[-1])

print(list_to_string(some_list))