3 Must-Know Concepts About Python Data Structures | by Soner Yıldırım | Jul, 2023

Learn them to write efficient and robust programs

Photo by Ricardo Gomez Angel on Unsplash
  • Lists can have duplicate items but sets can’t.
  • You can update an item in a list but not in a tuple.
  • You can get the third item from a tuple but not from a set.

These are just a few things to know about Python data structures. There are surely reasons behind these differences, which make each one suitable for a particular task.

To write efficient Python scripts, one must know the key characteristics of these data structures as well as how to use them.

For instance, we can use sets to find the different items between two lists:

lst_1 = ["Jane", "Emily", "John", "Max", "Emily", "Jane", "Matt"]

lst_2 = ["Jane", "Matt", "John", "Jane", "Emily"]

# convert each list to a set, find the difference using subtraction
difference = list(set(lst_1) - set(lst_2))

# output

We’ll learn three must-know concepts about Python’s four built-in data structures: dictionary, set, list, tuple.

If a data structure is mutable, we can update its items or add new items to it.

  • List: mutable (we can add new items to a set and update existing ones)
  • Set: mutable (we can add new items to a set)
  • Dictionary: mutable (we can add new items to a set and update existing ones)
  • Tuple: not mutable

Let’s do a few examples to show how to add new items to a list, a set, and a dictionary.

# set
myset = set([1, 2, 3])
# output
{1, 2, 3, 4}

# list
mylist = [1, 2, 3]
# output
[1, 2, 3, 4]

# dictionary
mydict = {"John": 24, "Jane": 26}
mydict["Emily"] = 30
# output
{'John': 24, 'Jane': 26, 'Emily': 30}

We can add items to a tuple but it does not modify the tuple itself. Instead, we get a new tuple with new items added.

# tuple
mytuple = (1, 2, 3)
newtuple = mytuple + (4,)
# output
(1, 2, 3, 4)

Source link

Leave a Comment