Are Python lists and dictionaries immutable?

Data Structures- Lists, Tuples, Dictionaries, and Sets in Python

Rachel Aitaru

Mar 13, 2019·5 min read

I had quite a bit of a hard time figuring out how to do one of my assignments because I was still getting the hang of these data structures. But after going through this lesson, it helped me get a better understanding of how I can use them. Below is a summary of my learnings.

A List, Set, Tuple, and Dictionary are one of the most common and basic data structures in Python. Data structures are containers that organize and group data types together in different ways.

Mutability and Order

Mutability is about whether or not we can change an object once it has been created. If an object can be changed then it is called mutable. However, if an object cannot be changed with creating a completely new object, then the object is considered immutable.

Order is about whether the position[index] of an element in the object can be used to access the element.

Lists

Lists can contain any mix and match of the data types you have seen so far. You can create a list with square brackets like below. Lists are both mutable and ordered.

list_of_random_things = [1, 3.4, 'a string', True]

Tuples

A tuple is a data type for immutable ordered sequences of elements. They are often used to store related pieces of information. Tuples are similar to lists in that they store an ordered collection of objects which can be accessed by their indices. Unlike lists, however, tuples are immutable you cant add and remove items from tuples, or sort them in place.

location_a = [13.4125, 103.866667]
location_b = 13.4125, 103.866667

The parentheses are optional when defining tuples, and programmers frequently omit them if parentheses dont clarify the code. location_a and location_b are the same.

Sets

A set is a data type for mutable unordered collections of unique elements. One application of a set is to quickly remove duplicates from a list.

numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set[numbers]
print[unique_nums]
#Output would be:
{1, 2, 3, 6}

Dictionaries

A dictionary is a mutable data type that stores mappings of unique keys to values. Heres a dictionary that stores elements and their atomic numbers.

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}

Dictionaries can have keys of any immutable type, like integers or tuples, not just strings. Its not even necessary for every key to have the same type! We can look up values or insert new values in the dictionary using square brackets that enclose the key.

Summary of Lists, Tuples, Sets, and Dictionaries
  • *You can use curly braces to define a set like this: {1, 2, 3}. However, if you leave the curly braces empty like this: {} Python will instead create an empty dictionary. So to create an empty set, use set[].
  • * *A dictionary itself is mutable, but each of its individual keys must be immutable. You can find out why here.

How I used these lessons to solve a challenge:

Write a function that takes a string and returns a tuple containing a new string made of all and only the vowels from the original string and the number of duplicates in the original string. Only the first instance of the vowel is considered.

For example:

countVowels[dahdah] # will return [a, 3]

countVowels[drink water] # will return [iae, 1]

image 1- tuple.py, image 2-tuple2.py

Description of the code above:

  1. Any line or statement that begins with [#] symbol is a comment and simply explains the code below it.
  2. The only difference between image 1 & 2 is that image1 prompts the person to enter any word in [line 6] and in image 2 [line 16] passes a value to the function in [line 2] i.e dahdah is assigned to the word parameter. Otherwise, the rest of the lines are the same.
  3. Going with image 2 onwards. Line 3 Creates a list of vowel letters that we shall use to come up with one of the tuple elements [my_string].
  4. line 6 [x for x in word if x in vowels] retrieves all and only the letters in word that are also in vowels. But the output for this might have duplicate letters depending on the value for word and remember only the first instance of the vowel is considered. Using dahdah, the output would be [a,a]. So we convert the list to a set by using set[] method which removes all the duplicate elements to give us {a}.
  5. line 7 The output of line 6 will bring a set of elements separated by commas[,] if the elements are more than one. Remember the tuple element [my_string] is supposed to be a string containing the vowel letters. so we use .join[vowel_word] which is a string method that takes a list of strings in vowel_word as an argument and returns a string consisting of the list elements joined by a separator string[Whats between the ]. In this case, it makes the element one string because theres nothing between the quotes.
  6. line 10 We are counting the number of duplicates in the original string. First, we have to find which letters are duplicate or appear more than once using [x for x in word if word.count[x]>1] and the output would be [d,a, h, d, a, h]. After getting the duplicate letters, we have to remove their duplicates using the set[] method so that they appear once like this {d, a, h}.
  7. line 13 Creates a tuple- my_tuple with two elements; my_string- a new string made of all and only the vowels from the original string and len[duplicates]- the number of duplicates in the original string. The len[] method counts the number of elements in the duplicates list[{d, a, h}].
  8. line 14 displays the output[value of my_tuple] to the screen.
Output for image2- tuple2.py

If you found this helpful, feel free to share or comment.

Video liên quan

Chủ Đề