Python – Part #2 (Data Collections)

DATA COLLECTION

There are four built-in collections of data types in Python, each one with different qualities for particular purposes.

LISTS:

– Lists are used to store multiple items in a single variable and are created using square brackets [ ].

– List items can be ordered, they are changeable, allow duplicate values, and can contain any data type.

– List items are indexed, the first item has index [0], the second item has index [1], and so on.

– ” : ” colon is used inside the index as a range.

– To check the type of list we are using we write print (type(list_name))

Example #1:

numbers = [“1”, “2”, “3”]

print(numbers[0])

Output:

        >> 1

Example #2:

list1 = [“letter”, 1.4, True, False, “name”, 17]

print(list1[1:4])

Output:

        >> [1.4, True, False]

TUPLES:

Tuples are used to store multiple items in a single variable, however, they are a collection that is ordered and unchangeable.

As opposed to the list syntax, the tuples are written with round brackets ( ).

They can contain multiple data types as well.

Example #1:

numbers = (“1”, “2”, “3”)

print(numbers[2])

Output:

        >> 3

Example #2:

numbers = (“1”, “2”, “3”)

print(type(numbers))

        >> <class ‘tuple’>

SETS:

A set is a collection of data types that is unordered, unchangeable, unindexed, and duplication is not allowed.

A set uses curly brackets { }.

Example #1:

numbers = {“1”, “2”, “3”}

print(numbers[2])

Output:

        >> TypeError: ‘set’ object is not subscriptable     #Error due to unindexation.

Example #2:

numbers = {“1”, “2”, “3”}

print(numbers)

Output:

        >> {‘3’, ‘2’, ‘1’}

DICTIONARIES:

They are ordered, changeable, and do not accept duplicates.

Dictionaries are used to store data values in key : value pairs, and are written with curly brackets.

A visual example of key: value pairs:

Example #1:

car_company = {
  “brand”: “Ford”,
  “model”: “Mustang”,
  “year”: 2022
}
print(car_company[“brand”])
 
Output:
 
        >>  Ford
 
UNPACKING:
 
This technique is mostly used to shorten the code, improve readability, and efficiency.
 
List:
 
numbers = [10,20,30]
 
Example of inefficient code:
 
x = numbers[0]
y = numbers[1]
z = numbers[2]
 
Example of efficient code:
 
x, y, z = numbers
 
The list of numbers will assign its numbers according to the order of the variables.
 
METHODS
 
There are many quite useful methods we can include when we use the data collection Python facilities:
All of these methods can be used on mutable Python data collection, those that aren’t mutable have methods limitations.
 

variable.append (adds a new object)

variable.insert (index, object)

variable.remove (specific object)

variable.index(object in list) #returns index number.

variable.count (object)

variable.sort ( )

variable.reverse( )

variable.copy ( )

Mapping method for Dictionaries: variable.get (key) # Returns value pair