DEV Community

Cover image for Built-in Data Structures In Python
Tito
Tito

Posted on • Updated on

Built-in Data Structures In Python

Introduction

Python has always been classified as a general-purpose programming language due to it's versatility, from web dev to data science.
However, data has become a lifestyle and has to be considered during systems design. All the data collected needs to be store and accessed efficiently. To attain this , data structures come in hand.

1. What's a Data structure ?

A data structure is a specialized format for organizing, processing, retrieving and storing data.

Types of Data Structures

1. Built-in

As the name suggest, Built-in data structures are predefined data structures that come along with python.Can be accessed from any python environment.
a.Lists
They are used to store data of different data types in a sequential manner.Every member of the list are assigned unique address called index.The first member of a list is assigned number 0. Members of the list can accessed in two ways; Positive indexing(the most common method) and Negative indexing.All this will be demonstrated in examples.
List are created by assigning square rackets to a variable and add a values accordingly.
Implementation

#creating empty values
cars = []
print(cars)
#adding elements to a list
cars = ["Audi",3.2,"Subaru",5,"Romeo",432.789]
print(cars)
Enter fullscreen mode Exit fullscreen mode
Output:
[]
["Audi",3.2,"Subaru",5,"Romeo",432.789]
Enter fullscreen mode Exit fullscreen mode

List Methods

These are built-in operations for manipulating lists. We shall explore them with examples.

Methods Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Example

cars = ["Audi",3.2,"Subaru",5,"Romeo",432.789]
print(cars)
# append 
cars.append("Toyota")
print(cars)
#copy
cars_1 = cars.copy()
print(cars_1)
# clear
cars_1.clear()
print(cars_1)
# count
print(cars.count("Audi"))
# Extend
fruit = ["kiwi","cherry","grapes"]
city = ["morotro","iraq","texas","qalit"]
fruit.extend(city)
print(fruit)
# index
cars = ["Audi",3.2,"Subaru",5,"Toyota","Romeo",432.789]
print(cars.index("Toyota"))
#insert
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
#pop
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
Enter fullscreen mode Exit fullscreen mode
output:
["Audi",3.2,"Subaru",5,"Romeo",432.789]
["Audi",3.2,"Subaru",5,"Romeo",432.789,"Toyota"]
["Audi",3.2,"Subaru",5,"Romeo",432.789]
[]
1
["kiwi","cherry","grapes","morotro","iraq","texas","qalit"]
4
['apple','orange','banana', 'cherry']

['apple','cherry']

Enter fullscreen mode Exit fullscreen mode

b.Tuples

These are data structure that store an ordered sequence of values. Tuples are immutable. This means you cannot change the values in a tuple. Tuples are defined with parenthesis.

NOTE

  • Tuples allow duplicate values
  • it is not necessary to enclose the tuple elements in parentheses
  • Tuples allow use of heterogeneous data

Implementation

realk = ("Texas","Estonia","Monaco")
print(realk)
# duplicate values
realk1 = ("Texas","Estonia","Monaco","Texas")
print(realk1)
# No parentheses
realk = 'Texas','Estonia','Monaco'
print(realk)
# Heterogeneous data
employee=(1, 'Steve', True, 25, 12000)
print(employee)
Enter fullscreen mode Exit fullscreen mode
output:
('Texas','Estonia','Monaco')
('Texas','Estonia','Monaco','Texas')
('Texas','Estonia','Monaco')
(1, 'Steve', True, 25, 12000)

Enter fullscreen mode Exit fullscreen mode

Tuples Operations

Tuple is unchangeable. So, once a tuple is created, any operation that seeks to change its contents is not allowed. For instance, trying to modify or delete an element of any tuple will result in an error.

Operator
The + operator returns a tuple containing all the elements of the first and the second tuple object.

Example

t1=(1,2,3)
t2=(4,5,6)         
t1+t2              
(1, 2, 3, 4, 5, 6) 
t2+(7,)            
(4, 5, 6, 7)
Enter fullscreen mode Exit fullscreen mode
Operator
The * operator Concatenates multiple copies of the same tuple.

Example

>>> t1=(1,2,3)
>>> t1*4                             
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
Enter fullscreen mode Exit fullscreen mode
Operator
The [] operator Returns the item at the given index. A negative index counts the position from the right side.

Example

>>> t1=(1,2,3,4,5,6)     
>>> t1[3]                
4                        
>>> t1[-2]               
5
Enter fullscreen mode Exit fullscreen mode
Operator
The [:] operator returns the items in the range specified by two index operands separated by the : symbol.
If the first operand is omitted, the range starts from zero. If the second operand is omitted, the range goes up to the end of the tuple.
>>> t1=(1,2,3,4,5,6) 
>>> t1[1:3]              
(2, 3)                   
>>> t1[3:]               
(4, 5, 6)                
>>> t1[:3]               
(1, 2, 3)
Enter fullscreen mode Exit fullscreen mode
Operator
The in operator returns true if an item exists in the given tuple.

Example

>>> t1=(1,2,3,4,5,6) 
>>> 5 in t1
True                
>>> 10 in t1 
False
Enter fullscreen mode Exit fullscreen mode
Operator
The not in operator returns true if an item does not exist in the given tuple.

Example

>>> t1=(1,2,3,4,5,6) 
>>> 4 not in t1 
False                    
>>> 10 not in t1
True
Enter fullscreen mode Exit fullscreen mode

c.Dictionary

Dictionaries are used to store data values in key:value pairs.

Characteristics of Dictionaries

  • They are ordered:The items have a defined order, and that order will not change.
  • They are Changeable: that we can change, add or remove items after the dictionary has been created.
  • They do not allow duplicates: cannot have two items with the same key
  • The values of a dictionaries can be of any data type.

NB: As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

Dictionary methods

Method Description
clear() Removes all the elements from the dictionary

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
members.clear()
print(members)

Output:
{}
Enter fullscreen mode Exit fullscreen mode
Method Description
copy() Returns a copy of the dictionary

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
copy_members = members.copy()
print(copy_members)

Output:
{'sales':'Rhorda','Accounts':'Mustafa','Technical':'Naliaka'}
Enter fullscreen mode Exit fullscreen mode
Method Description
fromkeys() Returns a dictionary with the specified keys and value.Can be used to make dictionary with the same values

Example

departmet = ("account","IT","Engineering")
members = ("Tityo")
dict_1 = dict.fromkeys(departmet,members)
print(dict_1)

Output:
{'account': 'Tityo', 'IT': 'Tityo', 'Engineering': 'Tityo'}
Enter fullscreen mode Exit fullscreen mode
Method Description
get() Returns the value of the specified key

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
Acc_1 = members.get("Accounts")
print(Acc_1)

Output:
Mustafa
Enter fullscreen mode Exit fullscreen mode
Method Description
items() Returns a list containing a tuple for each key value pair.The view object contains the key-value pairs of the dictionary, as tuples in a list.

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
Acc_1 = members.items()
print(Acc_1)

Output:
dict_items([('sales', 'Rhorda'), ('Accounts', 'Mustafa'), ('Technical', 'Naliaka')])

Enter fullscreen mode Exit fullscreen mode
Method Description
keys() Returns a list containing the dictionary's keys.The view object contains the keys of the dictionary, as a list.

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
Acc_1 = members.keys()
print(Acc_1)

Output:
dict_items(['sales','Accounts','Technical'])
Enter fullscreen mode Exit fullscreen mode
Method Description
pop() Removes the element with the specified key

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
Remove_member = members.pop("sales")
print(Remove_member)

Output:
{'Accounts':'Mustafa','Technical':'Naliaka'}
Enter fullscreen mode Exit fullscreen mode
Method Description
popitem() Removes the last inserted key-value pair

NB:Before Python 3.7, the popitem() method removes a random item.
Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
Remove_member = members.popitem()
print(Remove_member)

Output:
{'Accounts':'Mustafa','Accounts': 'Mustafa'}
Enter fullscreen mode Exit fullscreen mode
Method Description
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
Remove_member = members.setdefault("sales","phagra")
print(Remove_member)
Output:
Rhorda
Enter fullscreen mode Exit fullscreen mode
Method Description
update() Updates the dictionary with the specified key-value pairs.The specified items can be a dictionary, or an iterable object with key value pairs.

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
New_member = members.update({"Engineering":"phagra"})
print(New_member)
Output:
{'sales':'Rhorda','Accounts':'Mustafa','Technical':'Naliaka','Engineering':'phagra'}
Enter fullscreen mode Exit fullscreen mode
Method Description
values() Returns a list of all the values in the dictionary.The view object contains the values of the dictionary, as a list.The view object will reflect any changes done to the dictionary

Example

members = {
  "sales": "Rhorda",
  "Accounts": "Mustafa",
  "Technical": "Naliaka"
          }
member_values = members.values()
print(member_values)
Output:
dict_values(['Rhorda','Mustafa','Naliaka'])
Enter fullscreen mode Exit fullscreen mode

d.Sets
A set is an unordered collection of items.

Characteristics of Sets

  • Every set element is unique (no duplicates)
  • They must be unchangeable.
  • It is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function.

Set Methods

Method Description
add() Adds an element to the set

Example

x = {"facebook", "instagram", "whatsapp"}
x.add("twitter")
print(x)

Output:
{'facebook', 'instagram', 'whatsapp','twitter'}
Enter fullscreen mode Exit fullscreen mode
Method Description
clear() Removes all the elements from the set

Example

x = {"facebook", "instagram", "whatsapp"}
x.clear()
print(x)

Output:
set()
Enter fullscreen mode Exit fullscreen mode
Method Description
copy() Returns a copy of the set

Example

x = {"facebook", "instagram", "whatsapp"}
y = x.copy()
print(y)

Output:
{'facebook','instagram', 'whatsapp'}
Enter fullscreen mode Exit fullscreen mode
Method Description
difference() Returns a set containing the difference between two or more sets
Method Description
difference_update() Removes the items in this set that are also included in another, specified set
Method Description
discard() Remove the specified item
Method Description
intersection() Returns a set, that is the intersection of two other sets
Method Description
intersection_update() Removes the items in this set that are not present in other, specified set(s)
Method Description
isdisjoint() Returns whether two sets have a intersection or not
Method Description
issubset() Returns whether another set contains this set or not
Method Description
issuperset() Returns whether this set contains another set or not
Method Description
pop() Removes an element from the set randomly

Example

x = {"facebook", "instagram", "whatsapp"}
x.pop()
print(x)

Output:
{'instagram','whatsapp'}
Enter fullscreen mode Exit fullscreen mode
Method Description
remove() Removes the specified element

Example

x = {"facebook", "instagram", "whatsapp"}
x.remove("facebook")
print(x)

Output:
{'instagram','whatsapp'}
Enter fullscreen mode Exit fullscreen mode
Method Description
symmetric_difference() Returns a set with the symmetric differences of two sets

Example

x = {"facebook", "instagram", "whatsapp"}
y = {"google", "microsoft", "facebook"}

x.symmetric_difference(y)
print(x)

Output:
{'instagram','whatsapp','google','microsoft'}
Enter fullscreen mode Exit fullscreen mode
Method Description
symmetric_difference_update() inserts the symmetric differences from this set and another

Example

x = {"facebook", "instagram", "whatsapp"}
y = {"google", "microsoft", "facebook"}

x.symmetric_difference_update(y)
print(x)

Output:
{'instagram','whatsapp','google','microsoft'}
Enter fullscreen mode Exit fullscreen mode
Method Description
union() Return a set containing the union of sets

NB:You can specify as many sets you want, separated by commas.
It does not have to be a set, it can be any iterable object.
If an item is present in more than one set, the result will contain only one appearance of this item.

Example

x = {"facebook", "instagram", "whatsapp"}
y = {"google", "microsoft", "apple"}
w = {"google","twitch","whatsapp"}
x.union(y,w)
print(x)

Output:
{'facebook','instagram','microsoft','apple','whatsapp','google','twitch'}
Enter fullscreen mode Exit fullscreen mode
Method Description
update() Update the set with the union of this set and others

Example

x = {"facebook", "instagram", "whatsapp"}
y = {"google", "microsoft", "apple"}
x.update(y)
print(x)

Output:
{'facebook','instagram','whatsapp','google','microsoft','apple'}
Enter fullscreen mode Exit fullscreen mode

In my next article, I will be discussing User-defined Data Structures in python. Stay tuned by following me.
Your comment is highly-valued

RESOURCES

Top comments (2)

Collapse
 
yanivnoema profile image
Yaniv Noema

Very good 👏

Collapse
 
titusnjuguna profile image
Tito

Thank you sir