got SyntaxError while building simple function - 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: got SyntaxError while building simple function (/thread-24442.html) |
got SyntaxError while building simple function - zarize - Feb-14-2020 Hi guys, How can i set up simple function to unpack a list? i was trying to: def list_to_string(x): x = *x return xbut then i can see SyntaxError: can't use starred expression here RE: got SyntaxError while building simple function - DeaD_EyE - Feb-14-2020 What should this * expression do?What do you want to achieve? If you want to concatenate the items in the list to a str , you could use the join method on str .your_list = ['Hello', 'World'] the_seperator = " " my_new_str = the_seperator.join(your_list) print(my_new_str)Usually it's written more dense: my_new_str = " ".join(your_list)If the list does not only contain str objects, you need to convert them.your_list = ['Hello', 'World', None, True, False, ...] the_seperator = " " to_str = map(str, your_list) # lazy evaluation # apply str(item) for each item in your_list my_new_str = the_seperator.join(to_str) print(my_new_str) Unpacking arguments in function signature: def greet(greeting, times, *names): for name in names: for _ in range(times): print(greeting.format(name)) greet("Hello {}.", 2, "zarize", "DeaD_EyE") # ^^^^^^^^^^^^^^^^^^^^^ <- *names Unpacking keyword arguments in function signature: def cook(**indigrents): for indigrent, how_often in indigrents.items(): print(indigrent.capitalize(), 'x', how_often) cook(beer=3, bannana=1) # ^^^^^^^^^^^^^^^^ <- **indigrents RE: got SyntaxError while building simple function - zarize - Feb-14-2020 Thank you for your input :) My goal was to create simple function which would transfer list into a string ideally (just by passing an argument to function and it would return whole list as string) Lets say i have mylist = [ABC, 123, 456]Ideally i would like to get '123456' I know that i can do it on many ways such as: mylist = mylist.split()[1:3] mylist = ''.join(mylist)or: mylist = mylist[1] + mylist[2]SOLVED: Usually it's written more dense: Python Code: (Double-click to select all) 1 my_new_str = " ".join(your_list) Thank you.. i am dumb :P |