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
  A more efficient code titanif 2 514 Oct-17-2023, 02:07 PM
Last Post: deanhystad
  Cleaning my code to make it more efficient BSDevo 13 1,403 Sep-27-2023, 10:39 PM
Last Post: BSDevo
  Making a function more efficient CatorCanulis 9 1,898 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 1,827 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  I there a more efficient way of printing ? Capitaine_Flam 7 3,560 Dec-01-2020, 10:37 AM
Last Post: buran
  A more efficient way of comparing two images in a python vukan 0 2,043 Mar-17-2020, 11:39 AM
Last Post: vukan
  how to make iterative search more efficient renergy 2 2,288 Jan-03-2020, 03:43 PM
Last Post: stullis
  Simple problem. looking for an efficient way silverchicken24 3 2,352 Oct-14-2019, 07:13 PM
Last Post: Larz60+
  Most efficient way to define sub keys of a dictionary? wrybread 1 2,129 Feb-21-2019, 12:23 AM
Last Post: snippsat
  Efficient way of iterating a list of records anguis 4 3,076 Feb-19-2019, 03:39 AM
Last Post: scidam

Forum Jump:

User Panel Messages

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