2

I have a function I need to call with a certain amount of parameters based on certain variables, something like this:

self.model = Gtk.ListStore(str for i in len(dictionary))

Of course that doesn't work since str for i in len(dictionary) results in a list: [str, str, str, str]

While I can always just write 4 lines and a bunch of if statements for each alternative there must be a better way of doing this.

0

3 Answers 3

4

Perhaps you could use the * syntax?

self.model = Gtk.ListStore(*[str for i in len(dictionary)])

The * unpacks the list and passes each element as a separate argument to the function.

Sign up to request clarification or add additional context in comments.

2 Comments

Great! Might want to add that I alsoneeded range(len(dictionary)) as ints aren't iterable (doh)
yes (*[str(x) for x in range(len(dict))]) should work, but you should know that the liststore act like a python list.Avoiding dict and using list of tuples may be much more efficient.
2

To repeat the same value x times just multiply it by an int:

Gtk.ListStore(*[str]*len(dictionary))

For arbitrary generators, put a star before a generator to unpack it:

Gtk.ListStore(*(x for bar in spam))

Note that there's no need for a temporary list.

3 Comments

This is the cleanest for my use case.
Would the first example be a list comprehension rather than a generator, or is it something else altogether?
@JV: the first example is just a multiplication operator. When applied to a sequence (list, string etc), it returns this sequence repeated x times: docs.python.org/2/reference/…
2

If the function you are calling uses *args, then you can use what I believe is called the splat operator - *.

Example:

def f(*arbitrary_amount_of_arguments):
    for i in arbitrary_amount_of_arguments:
        print(i)

>>> f("a", "b", "c")
a
b
c
>>> f(*[1, 2, 3, 4, 5, 6, 7])
1
2
3
4
5
6
7

Or in your specific example:

self.model = Gtk.ListStore(*(str for i in range(len(dictionary))))

I would also like to question if you want to pass the inbuilt string class str for i in range(len(dictionary)).

Edit: self.model = Gtk.ListStore(*(str for _ in enumerate(dictionary))) or self.model = Gtk.ListStore(*[[str] * len(dictionary)) are probably better than my previous suggestion in that they are more Pythonic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.