0

Is there any other value except an one-char string such that:

v = '?' # any char
assert [x for x in v] == [x for x in [v]]

? I'm asking because due to this "anomaly" I have to treat strings specially.


I tried to make my question minimal. To answer the comments, it is related to an API accepting a sequence of items, but in vast majority of cases only one item is passed, so it was decided to accept also a single item.

By "anomaly" I mean that it is similar to the famous math problem of a set containing itself.

VPfB
  • 14,927
  • 6
  • 41
  • 75
  • 2
    Why the use of `[v]` and what anomalies ? – han solo Mar 18 '19 at 15:51
  • 4
    Possible XY problem: in what context do you need to treat a `str` value as effectively non-iterable? – chepner Mar 18 '19 at 15:51
  • Any object that implements iteration really… – deceze Mar 18 '19 at 15:51
  • 1
    In Python, a char can only be expressed as a string, which is a collection of chars, so not unlike a list which is also a collection. – quamrana Mar 18 '19 at 15:51
  • 1
    Compare against `v = 'abc'`, and the reason for the behavior will be obvious. – Charles Duffy Mar 18 '19 at 15:52
  • ...so anyhow -- *yes*, if you want to treat strings differently from other iterables, you need to implement that in your code. Was that your question? (I'm not really sure I *see* a specific question at all here, as opposed to an observation). – Charles Duffy Mar 18 '19 at 15:53
  • 1
    `l = []; l.append(l)`, but most of the cases where you'd want to treat strings differently, it's only strings and bytestrings, even if something else might have the same iteration behavior, and even though iterating over a bytestring produces ints now. – user2357112 Mar 18 '19 at 15:55
  • 1
    I think the point here is that Python has no Char type. It instead uses a single character string to represent a single char. This DOES lead to inconsistencies in behavior surrounding the string type. I think the OPs question/idea is a valid one. I don't know that there's any answer though. I think you do need to add special cases to deal with strings that are really individual char, and also with the fact that you might want to consider a string a non-iterable thing, even though it is. - I've always thought it wrong that a string object acts so easily like an array of characters. – CryptoFool Mar 18 '19 at 16:23
  • Related, maybe even a dupe: https://stackoverflow.com/questions/836387/how-can-i-tell-if-a-python-variable-is-a-string-or-a-list – snakecharmerb Mar 20 '19 at 08:25

0 Answers0