π Collections in Python
Contents
π Collections in Python#
Lists#
Lists are defined using []
, items in a list are separated by ,
.
Lists are used to store multiple items in a single variable.
Lists are ordered#
list1 = [1, 2, 3, 4]
list2 = [2, 3, 4, 1]
[1, 2, 3, 4] == [2, 3, 4, 1]
False
You can add a value to a list.
This can be done with the built-in method
<obj>.append(<index>)
list1.append(5)
list1
[1, 2, 3, 4, 5]
You can remove items from a list
this can be done with the built-in method
<obj>.pop(<index>)
list1.pop(2)
3
list1
[1, 2, 4, 5]
Lists Allow Duplications#
list1 = [1, 1, 1]
list1
[1, 1, 1]
Changing a value of a list#
Note
Python supports indexing of ordered objects using `[{index}]`, it is important to note that the index starts at 0.Replacing a value
list1[0] = "Drexel"
list1
['Drexel', 1, 1]
Inserting a value
list1.insert(1, "Dragons")
list1
['Drexel', 'Dragons', 1, 1]
Sorting Lists#
list1 = [5, 2, 3, 1]
list1.sort()
list1
[1, 2, 3, 5]
list2 = ["Drexel", "Dragons"]
list2.sort()
list2
['Dragons', 'Drexel']
Lists can contain multiple data types#
list1 = ["Drexel", 1, 1.0]
print(type(list1[0]))
print(type(list1[1]))
print(type(list1[2]))
<class 'str'>
<class 'int'>
<class 'float'>
You can even store list of list
list2 = [list1, list1]
list2
[['Drexel', 1, 1.0], ['Drexel', 1, 1.0]]
or lists of lists of lists
list3 = [list2, list2]
list3
[[['Drexel', 1, 1.0], ['Drexel', 1, 1.0]],
[['Drexel', 1, 1.0], ['Drexel', 1, 1.0]]]
You can get the length of a list using the method len()
print(len(list1))
print(len(list2))
print(len(list3))
3
2
2
Tuple#
A tuple is a collection that can store multiple ordered items that are unchangeable.
Syntax
Tuples are made using ({obj}, {obj})thistuple = ("Drexel", "Dragons", list2)
print(thistuple)
('Drexel', 'Dragons', [['Drexel', 1, 1.0], ['Drexel', 1, 1.0]])
Usually tuples are used to move objects, which are then unpacked to be used.
statement = ("Drexel", "Dragons", "Football", 0)
(University, Mascot, Sport, losses) = statement
print(f"school: {University}")
print(f"Mascot: {Mascot}")
print(f"Sport: {Sport}")
print(f"Lifetime Losses: {losses}")
school: Drexel
Mascot: Dragons
Sport: Football
Lifetime Losses: 0