Python Forum
Is there a more efficient way to code this project?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a more efficient way to code this project?
#1
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?
Reply
#2
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))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I make this code more efficient and process faster? steven_ximen 0 403 Dec-17-2024, 04:27 PM
Last Post: steven_ximen
Question SOLVED: VS Code: Adding external directories to project? Calab 5 3,846 Aug-02-2024, 02:20 PM
Last Post: deanhystad
  A more efficient code titanif 2 1,196 Oct-17-2023, 02:07 PM
Last Post: deanhystad
  Cleaning my code to make it more efficient BSDevo 13 3,713 Sep-27-2023, 10:39 PM
Last Post: BSDevo
  Making a function more efficient CatorCanulis 9 3,589 Oct-06-2022, 07:47 AM
Last Post: DPaul
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 2,623 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  I there a more efficient way of printing ? Capitaine_Flam 7 4,963 Dec-01-2020, 10:37 AM
Last Post: buran
  Simple problem. looking for an efficient way silverchicken24 3 3,288 Oct-14-2019, 07:13 PM
Last Post: Larz60+
  Wine / liquor dispenser project code issue onlinegill 0 2,628 Nov-20-2018, 10:41 PM
Last Post: onlinegill
  Need help making code more efficient dhbergen 5 4,908 Apr-17-2018, 01:00 AM
Last Post: dhbergen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020