Data Structures

String and Tuple

Lesson

Here, we talk about 2 new data structures called "Strings" and "Tuples" that are different versions of an Array.

String

Strings are Arrays but with letters in them. Here's how you create a String:

image

In Python, once you've created a string, you're not allowed to change it, or you'll get an error. This is because strings are "immutable", which means they can't be changed or "mutated".

Sometimes it might look like you've changed a string. In reality, the computer is really just creating an entirely new string and copying all of the old values over to it. You never actually change the old string. Here's an example of this.

Here's what this looks like in memory:

image
image

Python made strings immutable on purpose. Imagine if you passed a String into a function, and then you looked at the string again and it was completely different. That would be pretty confusing. Immutability guarantees that this never happens.

A negative consequence of immutability is that it's very slow to append items to strings, since you have to create a whole new string each time you add anything.

Instead of building strings like above, a common trick is to store all the letters in an Array, since Arrays are mutable and let you to make changes quickly. You then make the Array into a String at the very end. Here's an example:

Tuple

A Tuple is an Array, but it's immutable just like a String. Tuples aren't very common, but they do show up sometimes.

Takeaways

String = Immutable Array with characters in it

Tuple = Immutable Array

Mark as Completed:
Submits:
test
Test your code to get an output here!