1

In Python

  • lists are mutable:

    >>> a = []
    >>> b = a
    >>> a += [1]
    >>> b == [1]
    True
    
  • strings are immutable:

    >>> a = ""
    >>> b = a
    >>> a += "1"
    >>> b != "1"
    True
    
  • and strings can be treated as lists in some ways:

    >>> "abc"[-1] == "c"
    True
    

    but

    >>> "abc"[-1] = "d"
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    

Is there a helpful way of thinking of how exactly strings are like lists? Clearly there are other differences between them:

>>> hash("a")
7392557238547012712
>>> hash(["a"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

But maybe this is just a side effect of (im-)mutability.

l0b0
  • 55,365
  • 30
  • 138
  • 223
  • @StephenRauch I don't understand what you mean. I'm trying to understand *what the differences are,* not how "big" they are. – l0b0 Aug 06 '19 at 02:26
  • @Chris I don't consider it a duplicate because this is specifically about the `str` vs. `list` types, not immutable values in general. – l0b0 Aug 06 '19 at 02:27
  • @StephenRauch No, the bold text is the question. "How exactly [do] strings differ from lists?" – l0b0 Aug 06 '19 at 02:28
  • in addition to being *mutable*, lists can hold any value type in any position, including references to objects, while a string (which is *immutable*) can only hold (Unicode) character values. characters in lists are actually strings. that means if a character is in some position of a list, it cannot be changed. but that position in the list can be changed to hold a different value, such as a different string. – Skaperen Aug 06 '19 at 02:35
  • Nominating to re-open because it's not about a confusion between mutability and "final" classes. – l0b0 Aug 06 '19 at 02:51
  • 2
    They are two completely different types. They both happen to be sequences. – juanpa.arrivillaga Aug 06 '19 at 02:53
  • 1
    @juanpa.arrivillaga OK, that would be a useful answer, especially when linked to the [documentation](https://docs.python.org/3/library/stdtypes.html#typesseq). – l0b0 Aug 06 '19 at 03:03
  • 2
    I think the question as it currently stands is too broad. There's no reason to expect two different Python types to behave the same. Asking "How is a string different from a list?" is like asking "Why is a raven like a writing desk?" ("I give it up," Alice replied: “What’s the answer?" "I haven't the slightest idea," said the Hatter). It might be more productive to ask about their *common* features which are presumably finite, rather than their differences, which could be unlimited. But even that might be too broad. – Blckknght Aug 06 '19 at 03:07
  • @Blckknght Good point; modified. – l0b0 Aug 06 '19 at 03:08

0 Answers0