πŸ“ 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]

You can add a value to a list.

  • This can be done with the built-in method <obj>.append(<index>)

list1.append(5)
list1

You can remove items from a list

  • this can be done with the built-in method <obj>.pop(<index>)

list1.pop(2)
list1

Lists Allow Duplications#

list1 = [1, 1, 1]
list1

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

Inserting a value

list1.insert(1, "Dragons")
list1

Sorting Lists#

list1 = [5, 2, 3, 1]
list1.sort()
list1
list2 = ["Drexel", "Dragons"]
list2.sort()
list2

Lists can contain multiple data types#

list1 = ["Drexel", 1, 1.0]
print(type(list1[0]))
print(type(list1[1]))
print(type(list1[2]))

You can even store list of list

list2 = [list1, list1]
list2

or lists of lists of lists

list3 = [list2, list2]
list3

You can get the length of a list using the method len()

print(len(list1))
print(len(list2))
print(len(list3))

Tuple#

A tuple is a collection that can store multiple ordered items that are unchangeable.

Note

Tuples are made using ({obj}, {obj})

thistuple = ("Drexel", "Dragons", list2)
print(thistuple)

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}")