Python data structures: tuple, dict and set
Peer uest
Cancel
Sign Up
Forget passwd??
Log In
blog
7
Python data structures: tuple, dict and set
0

In this article, we will explain some common data structures in python

tuple

tuple is a sequence of heterogenous objects. Once created, it cannot be updated (immutable)

  • Create a tuple
a_tuple = (10, 20, "John", [5, 6], ("John", 56))
  • Can be accessed using index
a_tuple[1]
  • A tuple can be created from other iterables (e.g. list)
users = ["David", "John", "Peter"]
users_tuple = tuple(users)

set

  • set is a collection of uniqure immutable objects.

Create a set

users = {"Peter", "David", "John"}
  • To add an element
users.add("Kevin")
  • To add multiple elements in one statement
users.update(["Rupert", "Kathy", "Adam"])
  • To delete an element
users.remove("John")

dict

  • dict is a hash map that stores items in key/value pairs.
ages = {"Joe": 32, "Peter": 21, "David": 33}
  • To access with a key
ages['David']
  • To iterate a dict
for k, v in ages.items()
    print('{k} -> {v}')

 

0
Add a Comment
×
×
×
×
Sign In