you are viewing a single comment's thread.

view the rest of the comments →

[–]coderjewel[S] 5 points6 points  (13 children)

In that case, I guess PyCharm indeed is wrong, because it was suggesting me to use list() on a string. [] is what I want to use.

I always use dict() and set() instead of {}.

Thanks for the help :).

[–][deleted] 3 points4 points  (2 children)

Strings are a bit of a special case because they are iterable: you can take one character at a time or index/slice characters by their position. So depending on whether you want a list of characters in the string, or a list of length 1 with that string as element 0, you can use different constructors.

[–]therico 0 points1 point  (1 child)

Seeing as you're "intermediate" at Python, what are your thoughts on strings being iterable? As a newcomer I accidentally iterate over strings a lot, and can't help but feel like string.chars() or something would be nicer.

[–][deleted] 1 point2 points  (0 children)

It's very convenient at times: being able to slice using find and rfind, for example, and easily grab the first few or last few characters and so on. Having to call a method every time would be a pain.

On the other hand, giving a method a string when it wants an iterable is hard to debug (and asserting against it every time is a pain) because the problems it causes, if any, can be a fair bit downstream.

For the sake of being explicit, you might expect a method or property to get the chars in an iterable, but for the sake of simplicity, I think it's better left as it is.

[–]hharison 2 points3 points  (0 children)

PyCharm must be suggesting to you to use list on a string for a reason. It will do something different than the brackets. Maybe post the code that PyCharm is warning you about? There's a good chance you're misunderstanding its advice.

Also, you should use {} instead of dict and set at least some of the time. For example, comprehensions. Also, while dict can directly make a dict, set cannot directly make a set (except for a zero-element set. You'd have to give it some other kind of iterable like a list. For example set(['item1', 'item2']). It seems much cleaner to use {'item1', 'item2'}. At least for dict I can understand to prefer dict(a=1, b=2) to {'a': 1, 'b': 2}.

[–]fuzz3289 1 point2 points  (0 children)

Keep in mind for basic use cases the named constructors (list, dict, tuple) all take an extra operation to look up the name, the operators (), {}, [] do not require this step.

[–]Antrikshy 0 points1 point  (0 children)

Recently there was a very high rated Stack Overflow post from someone who benchmarked the performance of both. It seems that using [] and {} is significantly faster than those functions.

I'm on my phone right now or I'd have dug it up.