Python Unit 3
Python Unit 3
There are four collection data types in the Python programming language:
Python Lists
List
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Example
Create a List:
List Items
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the
items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
List Length
To determine how many items a list has, use the len() function:
Example
Example
Example
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
It is also possible to use the list() constructor when creating a new list.
Example
Access Items
List items are indexed and you can access them by referring to the index number:
Example
-1 refers to the last item, -2 refers to the second last item etc.
Example
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
Note: The search will start at index 2 (included) and end at index 5 (not included).
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
By leaving out the end value, the range will go on to the end of the list:
Example
Example
This example returns the items from "orange" (-4) to, but NOT including "mango" (-1):
Example
Example
To change the value of items within a specific range, define a list with the new values, and
refer to the range of index numbers where you want to insert the new values:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example
Note: The length of the list will change when the number of items inserted does not match
the number of items replaced.
If you insert less items than you replace, the new items will be inserted where you specified,
and the remaining items will move accordingly:
Example
Change the second and third value by replacing it with one value:
Insert Items
To insert a new list item, without replacing any of the existing values, we can use the insert()
method.
Example
Note: As a result of the example above, the list will now contain 4 items.
Python - Add List Items
Append Items
To add an item to the end of the list, use the append() method:
Example
Insert Items
Example
Note: As a result of the examples above, the lists will now contain 4 items.
Extend List
To append elements from another list to the current list, use the extend() method.
Example
The extend() method does not have to append lists, you can add any iterable object (tuples,
sets, dictionaries etc.).
Example
Append Items
To add an item to the end of the list, use the append() method:
Example
There are several ways to join, or concatenate, two or more lists in Python.
Example
Another way to join two lists is by appending all the items from list2 into list1, one by one:
Example
for x in list2:
list1.append(x)
print(list1)
Or you can use the extend() method, which purpose is to add elements from one list to
another list:
Example
list1.extend(list2)
print(list1)
Python has a set of built-in methods that you can use on lists.
Method Description
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
Python Tuples
Tuple
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.
Example
Create a Tuple:
Tuple Items
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.
Example
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple Items - Data Types
Example
Example
You can access tuple items by referring to the index number, inside square brackets:
Example
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the
tuple is created.
Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert
the list back into a tuple.
Example
print(x)
Add Items
Since tuples are immutable, they do not have a build-in append() method, but there are other
ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into
a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one
item, (or many), create a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
print(thistuple)
Note: When creating a tuple with only one item, remember to include a comma after the
item, otherwise it will not be identified as a tuple.
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Example
Example
Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you can use
the * operator:
Example
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Python Dictionary
Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with curly brackets, and have keys and values:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
When we say that dictionaries are ordered, it means that the items have a defined order, and
that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by
using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
print(len(thisdict))
Example
type()
From Python's perspective, dictionaries are defined as objects with the data type 'dict':
<class 'dict'>
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
x = thisdict.get("model")
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
x = thisdict.keys()
The list of the keys is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the keys list.
Example
Add a new item to the original dictionary, and see that the keys list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
car["color"] = "white"
Get Values
The values() method will return a list of all the values in the dictionary.
Example
x = thisdict.values()
The list of the values is a view of the dictionary, meaning that any changes done to the
dictionary will be reflected in the values list.
Example
Make a change in the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
car["year"] = 2020
Example
Add a new item to the original dictionary, and see that the values list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
car["color"] = "red"
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
x = thisdict.items()
The returned list is a view of the items of the dictionary, meaning that any changes done to
the dictionary will be reflected in the items list.
Example
Make a change in the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
car["year"] = 2020
Example
Add a new item to the original dictionary, and see that the items list gets updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
car["color"] = "red"
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
You can change the value of a specific item by referring to its key name:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary
The update() method will update the dictionary with the items from the given argument.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding an item to the dictionary is done by using a new index key and assigning a value to
it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Update Dictionary
The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item
is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)