WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Python Β· Basic Β· question 11 of 100

What is the difference between mutable and immutable data types in Python? Can you provide examples of each?

πŸ“• Buy this interview preparation book: 100 Python questions & answers β€” PDF + EPUB for $5

In Python, data types can be classified as either mutable or immutable. A mutable data type is one that can be changed after it has been created, while an immutable data type is one that cannot be changed after it has been created.

Here are some examples of mutable data types in Python:

Lists: Lists are mutable in Python. You can add, remove, or modify elements of a list after it has been created. Here is an example:

    my_list = [1, 2, 3]
    my_list.append(4) # add an element to the list
    my_list[0] = 5 # modify an element in the list

Dictionaries: Dictionaries are also mutable in Python. You can add, remove, or modify key-value pairs in a dictionary after it has been created. Here is an example:

    my_dict = {'a': 1, 'b': 2, 'c': 3}
    my_dict['d'] = 4 # add a key-value pair to the dictionary
    del my_dict['a'] # remove a key-value pair from the dictionary

Here are some examples of immutable data types in Python:

Strings: Strings are immutable in Python. Once a string has been created, you cannot change its contents. Here is an example:

    my_string = 'hello'
    # This will raise an error:
    # my_string[0] = 'H'

Tuples: Tuples are also immutable in Python. Once a tuple has been created, you cannot add, remove, or modify its elements. Here is an example:

    my_tuple = (1, 2, 3)
    # This will raise an error:
    # my_tuple[0] = 4

Numbers: Numbers (integers, floats, etc.) are immutable in Python. Once a number has been created, you cannot change its value. Here is an example:

    my_number = 42
    # This will raise an error:
    # my_number += 1

In general, mutable data types are useful when you need to change the contents of a data structure over time, while immutable data types are useful when you need to ensure that the contents of a data structure cannot be changed accidentally. By using the appropriate data type for your needs, you can write more efficient, reliable, and bug-free code in Python.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview β€” then scores it.
πŸ“ž Practice Python β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Python questions & answers β€” PDF + EPUB for $5

All 100 Python questions Β· All topics