Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension in function arguments

In Python 2.7.1, I'm trying to provide a list of messages as the first argument, and a list of colors as the second argument. I want the second argument to default to a list of whites if it's not provided. This is the way I tried to do it:

def multicolor_message(msgs, colors=[libtcod.white for x in len(msgs)]):
#function body

libtcod.white is a part of the library I'm using and is in no way causing any problems. The compiler says the variable msgs is not defined. Obviously the msgs variable doesn't exist in this scope, but I need to create a list of appropriate length and assign it to colors. What is the cleanest way to do this?

like image 244
boobookum Avatar asked Dec 31 '12 13:12

boobookum


People also ask

Can we use function in list comprehension?

Answer. Yes, the variable in the for of a list comprehension can be used as a parameter to a function.

Can a list be a function argument?

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

Is Python list comprehension functional?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

What does a list comprehension do?

List Comprehension provides a concise way to create lists. List Comprehension is the proper “pythonic” way of building an accessible, concise, and fast way to build lists. It allows one to perform complex operations on lists using a single line.


1 Answers

I would do it like this:

def multicolor_message(msgs, colors=None):
  if colors is None:
    colors=[libtcod.white for x in len(msgs)]
like image 137
piokuc Avatar answered Oct 08 '22 17:10

piokuc