2

In modules where a set of string literals is needed it can be declared as

values = ['hello', 'world']

But I have seen many experienced python programmers write

values = 'hello world'.split()

obviously considering it more readable. (I also think I have seen this in the python standard library source, but I'm not sure)

Does any python guide cite either of them as the preferred style, or does it come down to personal preference?

0

3 Answers 3

1

In some instances, when you have longer strings, it's shorter and arguably more readable to use a .split() than to write out a list.

In your case, with a small string, it doesn't really matter; I would use just a list because .split() is longer. It really depends on your preference.

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

Comments

1

values = ['hello', 'world'] should be more efficient. Also explicitly shows that values is a list of strings.

Comments

0

We can look at the source code.

split source code

It starts by initializing a new list:

PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));

Then doing the separator parameter lookup:

    while ((j < str_len) && (maxcount-- > 0)) {
        for(; j < str_len; j++) {
            /* I found that using memchr makes no difference */
            if (str[j] == ch) {
                SPLIT_ADD(str, i, j);
                i = j = j + 1;
                break;
            }
        }
    }

SPLIT_ADD actually calls PyList_SET_ITEM which inserts a certain object to the memory array.

Conclusion

Even without actually checking time differences, I can only assume that this lookup will be slower (even if a bit) than strictly initializing a list.

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.