Hello, and welcome to Part 3 of the series “Introduction to Python Programming” If you have not gone through the previous episode, kindly find the links below.
introduction to Python programming - part one
Introduction to Python programming - part two
Boolean Values
You can evaluate any expression in Python and get one of two answers, True or False.
Python delivers the Boolean result after evaluating the expression when two values are being compared:
print(20 > 10) #returns True
print(20 == 10) #returns False
print(20 < 10) #returns False
You can also check the comparison of two values with a conditional statement.
a = 1000
b = 100
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
#prints out b is not greater than a
Evaluate Values and Variables
You can evaluate any value using the bool() function, and it will return either True or False.
print(bool("Hello")) #returns True
print(bool(200)) #returns True
Most Values are True
If a value has content of any kind, it is evaluated to True almost immediately. Any string is True, except empty strings. Any number is True, except 0. Except for empty ones, every list, tuple, set, and dictionary are True.
The following will return true:
bool("Earth") #returns True
bool(4456) #returns True
bool(["apple", "cherry", "banana"]) #returns True
Certain values are false. Except for empty values like (), [], " ", the number 0, and the value None, there aren't many values that evaluate to False.
The following will be evaluated as false.
bool(False) #returns False
bool(None) #returns False
bool(0) #returns False
bool("") #returns False
bool(()) #returns False
bool([]) #returns False
bool({}) #returns False
Brace up, people, because we will be using the remaining part of this series to talk about Python data collections. They are very powerful tools at our disposal that will enable us to perform and create beautiful applications with Python. The four Python collections are
- Lists
- Tuple
- Sets
- Dictionary
Python Lists
Lists allow multiple elements to be maintained in a single variable.
Lists are created using square brackets.
Creating a list
Cities = ["Sydney", "New York", "London", "Paris"]
print(cities) #returns Sydney New York London Paris
List Items
List items can have duplicate values and are ordered and changeable.
List items are indexed; the first item has an index [0], the second item has an index [1], etc.
Properties of a list
a. Lists are ordered, which means the items in a list have a defined order in which they are arranged. When a new item is added to a list, it will be placed at the end of the list.
b. List items are changeable. You can add, or remove a list item after its creation.
c. Lists allow duplicates of list items, i.e., you can have the same items in a list.
Mylist = ["Sydney", "New York,", "London", "Paris", "New York", "London"]
print(Mylist)
d. You can determine the length of a list by using the len() function.
print(len(Mylist))
e. Any data type can be used for list items:
list1 = ["carrot", "pearl", "apple"] #list string data type
list2 = [10, 5, 2, 400, 3] #numeric list data type
list3 = [True, False, False] #boolean list data type
f. A list can contain different data types:
list1 = ["Hello", 600, False, 100, "male"]
#list with strings,numeric and boolean data types.
g. List() constructor: We can also use the list() constructor to create a new list instead of the square bracket.
thislist = list(("apple", "samsung", "xiaomi"))
# note the double round-brackets
print(thislist)
h. Finding items on a list: You can access list items by using the index number, which is listed with each item:
#Printing the third item on the list
thislist = ["apple", "samsung", "xiaomi"]
print(thislist[2]) #returns Xiaomi
NOTE: the first number has an index number of 0
Negative Indexing
Negative indexing means starting from the end
The last and next-to-last items are indicated by the numerals -1 and -2, respectively.
#Printing out the last item of a list
thislist = ["apple", "samsung", "xiaomi"]
print(thislist[-1]) #returns xiaomi
Range of Indexes
You can provide a range of indexes by indicating the range's beginning and ending points.
A new list containing the requested items will be returned when a range is specified.
#Return the third, fourth, and fifth item in the list
thislist = ["apple", "samsung", "xiaomi", "blackberry", "Nokia", "Tecno", "sony"]
print(thislist[2:5]) #returns xiaomi, blackberry and nokia
If the start value is omitted, the range will begin with the first item:
thislist = ["apple", "samsung", "xiaomi", "blackberry", "Nokia", "Tecno", "sony"]
print(thislist[:4])
#This code returns the items from the beginning but will exclude Nokia
The range will continue to the end of the list if the end value is omitted:
thislist = ["apple", "samsung", "xiaomi", "blackberry", "Nokia", "Tecno", "sony"]
#This code returns the items from “xiaomi” to the end
print(thislist[2:])
Range of Negative Indexes
If you want to start the search at the end of the list, enter negative indexes:
thislist = ["apple", "Samsung", "Xiaomi", "blackberry", "Nokia", "Tecno", "Sony"]
#This code returns the items from “blackberry” (-4) to, but NOT including “sony” (-1)
print(thislist[-4:-1])
Python Tuples
A tuple is a collection that is ordered and unchangeable.
Tuples are written in round brackets.
Creating a tuple
thistuple = ("java", "javascript", "python")
print(thistuple)
Tuple Items
Duplicate values are permitted for tuple items, which are ordered and immutable.
The first item in a tuple is indexed [0], and the second item is indexed [1], etc. The major difference between a list and a tuple, apart from how they are created, is that a list item can be changed, but a tuple item can't be changed.
To determine the tuple length, the len() function is also used.
print(len(thistuple))
Python will not recognize a single item as a tuple unless you add a comma after the item to make it a tuple.
thistuple = ("apple",)
print(type(thistuple))
Data types:
Any data type can be used for tuples. A tuple can contain numeric, string, or boolean values
The tuple() Constructor
Like a list, it is also possible to use the tuple() constructor to make a tuple.
#Using the tuple constructor to make a tuple
thistuple = tuple(("newyork", "lagos", "capetown"))
# note the double round-brackets
print(thistuple)
Set
Sets are written with curly brackets.
thisset = {"apple", "banana", "cherry"}
print(thisset)
Sets are unordered, so you cannot be sure in which order the items will appear
Set Items
Set items don't allow duplicate values, are unsorted, and can't be changed.
Set items can be of any data type, and a set can contain different data types
set1 = {"Europe", 324, True, 460, "male"}
print(set1)
The set() Constructor
It is also possible to use the set() constructor to make a set.
thisset = set(("apple", "mango", "pineaple"))
#note the double round-brackets
print(thisset)
Python Dictionaries
Python dictionaries make use of key: value pair storage for storing their data.
A dictionary is ordered, the items can be changed, and it doesn't allow duplicates of items.
The key: value pairs of data are wrapped inside a curly bracket.
#Creating a dictionary
thisdict = {
“Brand”: “Apple”,
“Model”: “Macbook pro”
“Year”: 2023
}
print(thisdict)
Dictionary Items
Items in the dictionary are arranged, editable, and do not permit duplication.
Key: value pairs are used to exhibit dictionary entries, and the key name can be used to refer to a particular entry.
#Print the “model” value of the dictionary
thisdict = {
“Brand”: “Apple”,
“Model”: “macbook pro”
“Year”: 2023
}
print(thisdict["brand"])
Dictionary Length
Use the len() function to find out how many items a dictionary has.
Data type in Dictionary
Items in dictionaries may have values of any data type.
The dict() Constructor
We can also use the dict() constructor to create a dictionary.
#Using the dict constructor to make a dictionary
thisdict = dict(name = "Akinnimi", age = 27, country = "Nigeria")
print(thisdict)
SUMMARY OF THE DIFFERENCES BETWEEN THE FOUR PYTHON DATA TYPE COLLECTIONS
Lists, tuples, sets, and dictionaries are all different types of data structures in Python, each with their own unique properties:
- Lists: Mutable: After creation, elements may be added, deleted, or updated. Ordered: Elements keep the order in which they were inserted. Allows elements to be duplicated.
- Tuples Immutable: Once created, an element cannot be altered. Ordered: Like lists, elements keep the order in which they were inserted. allows elements to be duplicated.
- Sets: Mutable: After creation, elements can be added or removed. Unordered: There is no innate order in the elements. prohibits the use of elements twice.
- Dictionary Mutable: After creation, key-value pairs may be added, changed, or eliminated. Unordered: Prior to Python 3.7, there was no assurance of order for dictionaries. Insertion order is preserved in Python 3.7 and beyond. Keys must be unchangeable and distinct. Values may include duplicate values and be of any type.
In conclusion, dictionaries are collections of key-value pairs with the option of order preservation, sets are unordered collections of unique components, and lists are flexible and ordered collections. Tuples are similar to lists but immutable.
There is a whole lot we can still do with the four data structures; I will recommend you read more about them in the official Python documentation.
Oldest comments (0)