Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Create Immutable Values in Python with Tuples

    Will ButtonWill Button

    The tuple is a new data structure to Python, and is an immutable sequence of values separated by commas. Learn how to create them in this lesson.

    pythonpython
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    To create a tuple in Python, you create name of your variable and you just add the items to it as a comma-separated list. You can add mixed data types to it as well. When we print it out, it looks much like a list, except for the fact that it's wrapped in parentheses versus square brackets, and as a matter of fact, to access individual elements, those are done the same way that you do with a list in Python.

    The difference between a list and a tuple is the fact that tuples are immutable and can't be changed once they're created. If we use the DRI method and specify our tuple you can see in the list of objects, methods, and properties that are available there's nothing for append, or add, or extend, or anything like that.

    If you need to change a tuple -- let me just show you this real quick -- here's the ID of our tuple named t. If we want to add a value to that, we have to recreate it, so we'll say t is equal to, and then specify all the items that we had in it before.

    Then, we can specify the new item that we want to add to it. If we take a look at the ID of it now, you can see that the ID number has changed to reflect the fact that we added fu to the end of it.

    Discuss

    Discuss