Learning Python

10. Python Collections

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered* and changeable. No duplicate members.

10.1. Lists

Lists are used to store multiple items in a single variable.

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    print(mylist)


if __name__ == "__main__":
    main()

Output

['apple', 'banana', 'cherry']

Lists can have duplicates and are ordered

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry", "apple", "cherry"]
    print(mylist)


if __name__ == "__main__":
    main()

List length len()

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    print(len(mylist))


if __name__ == "__main__":
    main()

A lists can contain different data types

#!/usr/bin/env python3

def main():
    mylist1 = ["apple", "banana", "cherry"]
    mylist2 = [1, 5, 7, 9, 3]
    mylist3 = [True, False, False]
    mylist4 = ["abc", 34, True, 40, "male"]

    print(mylist1)
    print(mylist2)
    print(mylist3)
    print(mylist4)


if __name__ == "__main__":
    main()

Using the type() function

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    print(type(mylist))


if __name__ == "__main__":
    main()
<class 'list'>

Uusing the list() constructor

#!/usr/bin/env python3

def main():
    mylist = list(("apple", "banana", "cherry"))
    print(mylist)


if __name__ == "__main__":
    main()

List items can directly be addressed

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    print(mylist[1])


if __name__ == "__main__":
    main()

Output:

banana
#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    print(mylist[-1])


if __name__ == "__main__":
    main()

Output:

cherry

Indexes

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(mylist[2:5])


if __name__ == "__main__":
    main()
#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(mylist[:4])
#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(mylist[2:])


if __name__ == "__main__":
    main()

Negative indexes

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(mylist[-4:-1])


if __name__ == "__main__":
    main()

Check if item exists

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    if "apple" in mylist:
        print("Yes, 'apple' is in the fruits list")


if __name__ == "__main__":
    main()

Changing an item

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist[1] = "blackcurrant"
    print(mylist)


if __name__ == "__main__":
    main()

Changing a range of items

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
    mylist[1:3] = ["blackcurrant", "watermelon"]
    print(mylist)


if __name__ == "__main__":
    main()
#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
    mylist[1:2] = ["blackcurrant", "watermelon"]
    print(mylist)


if __name__ == "__main__":
    main()
#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist[1:3] = ["watermelon"]
    print(mylist)


if __name__ == "__main__":
    main()

Append an item

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist.append("orange")
    print(mylist)


if __name__ == "__main__":
    main()

Insert items

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist.insert(2, "watermelon")
    print(mylist)


if __name__ == "__main__":
    main()

Extending a list

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    tropical = ["mango", "pineapple", "papaya"]
    mylist.extend(tropical)
    print(mylist)


if __name__ == "__main__":
    main()

Adding

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mytuple = ("kiwi", "orange")
    mylist.extend(mytuple)
    print(mylist)


if __name__ == "__main__":
    main()

Remove a specified item

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist.remove("banana")
    print(mylist)


if __name__ == "__main__":
    main()

Remove a specified index item

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist.pop(1)
    print(mylist)


if __name__ == "__main__":
    main()

Remove the last item

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist.pop()
    print(mylist)


if __name__ == "__main__":
    main()

Remove the first item

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    del mylist[0]
    print(mylist)


if __name__ == "__main__":
    main()

Delete the entire list

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    del mylist


if __name__ == "__main__":
    main()

Clear the list

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist.clear()
    print(mylist)


if __name__ == "__main__":
    main()

Sort the list

#!/usr/bin/env python3

def main():
    mylist = ["apple", "banana", "cherry"]
    mylist.sort()
    print(mylist)


if __name__ == "__main__":
    main()

10.2. Tuples

Tuples are used to store multiple items in a single variable, and are ordered, allow duplicates

def main():
    mytuple = ("apple", "banana", "cherry", "apple")
    print(mytuple)

Output

('apple', 'banana', 'cherry', 'apple')

The number of itmem in a tuple

def main():
    mytuple = ("apple", "banana", "cherry")
    print(len(mytuple))

Output

4

Determining the type

def main():
    mytuple = ("apple")
    print(type(mytuple))
    mytuple = ("apple",)
    print(type(mytuple))

Output

<class 'str'>
<class 'tuple'>

Creating a tuple using the constructor

def main():
    mytuple = tuple(("apple", "banana", "cherry"))
    print(mytuple)
('apple', 'banana', 'cherry')

Accessing items

def main():
    mytuple = ("apple", "banana", "cherry")
    print(mytuple[1])
    print(mytuple[:1])
    print(mytuple[1:])
    print(mytuple[:-1])

Check if an item exist in a tuple

def main():
    mytuple = ("apple", "banana", "cherry")
    if "apple" in mytuple:
        print("The apple is in mytuple")

Adding an item

def main():
    mytuple = ("apple", "banana", "cherry")
    a = list(mytuple)
    a.append("cherry")
    mytuple = tuple(a)
    print(mytuple)

Updating an item

def main():
    mytuple = ("apple", "banana", "cherry")
    a = list(mytuple)
    a[1] = "cherry"
    mytuple = tuple(a)
    print(mytuple)

Remove an item

def main():
    mytuple = ("apple", "banana", "cherry")
    a = list(mytuple)
    a.remove("apple")
    mytuple = tuple(a)
    print(mytuple)

Unpack a tuple

def main():
    mytuple = ("apple", "banana", "cherry")
    (a, b, c) = mytuple
    print(a)
    print(b)
    print(c)

Unpack a tuple with an asterix

def main():
    mytuple = ("apple", "banana", "cherry", "orange", "lemon")
    (a, b, c*) = mytuple
    print(a)
    print(b)
    print(c)
    (a, b*, c) = mytuple
    print(a)
    print(b)
    print(c)

Looping through a tuple

def main():
    mytuple = ("apple", "banana", "cherry")
    for a in mytuple:
        print(a)

    for i in range(len(mytuple)):
        print(mytuple[i])

    i = 0
    while i < len(mytuple):
        print(mytuple[i])
        i = i + 1

Joining tuples

def main():
    mytuple = ("apple", "banana", "cherry")
    myothertuple = ("orange", "lemon")
    myfulltuple = mytuple + myothertuple
    print(myfulltuple)
def main():
    mytuple = ("apple", "banana", "cherry")
    myfulltuple = mytuple * 2
    print(myfulltuple)

10.3. Sets

Sets are used to store multiple items in a single variable similar to lists, but doesn’t allow for duplicates in the set.

def main():
    myset = {"apple", "banana", "cherry", "apple"}
    print(myset)

The number of items in a set

def main():
    myset = {"apple", "banana", "cherry"}
    print(len(myset))

Which type is set?

def main():
    myset = {"apple", "banana", "cherry"}
    print(type(myset))

Using the constructor for sets

def main():
    myset = set(("apple", "banana", "cherry"))
    print(type(myset))

Add an item to a set

def main():
    myset = {"apple", "banana", "cherry"}
    print(myset)
    myset.append("peach")
    print(myset)

Add a set to a set

def main():
    myset = {"apple", "banana", "cherry"}
    myotherset = {"peach", "strawberry"}
    print(myset)
    myset.update(myotherset)
    print(myset)

Add any iterable to a set

def main():
    myset = {"apple", "banana", "cherry"}
    myotherset = ["peach", "strawberry"]
    print(myset)
    myset.update(myotherset)
    print(myset)

Removing an existing item from a set

def main():
    myset = {"apple", "banana", "cherry"}
    myset.remove("banana")
    print(myset)

Removing an possible existing item from a set

def main():
    myset = {"apple", "banana", "cherry"}
    myset.discard("peach")
    print(myset)

Removing the last item from a set

def main():
    myset = {"apple", "banana", "cherry"}
    myset.pop()
    print(myset)

Make the set empty

def main():
    myset = {"apple", "banana", "cherry"}
    myset.clear()
    print(myset)

Delete a set

def main():
    myset = {"apple", "banana", "cherry"}
    del myset
    print(myset)

Looping

def main():
    myset = {"apple", "banana", "cherry"}
    for a in myset:
        print(a)

Joining sets with an union

def main():
    myset = {"apple", "banana", "cherry"}
    myotherset = {"peach", "strawberry"}
    myfullset = myset.union(myotherset)
    print(myfullset)

Merging a set into a sets

def main():
    myset = {"apple", "banana", "cherry"}
    myotherset = {"peach", "strawberry"}
    myset.update(myotherset)
    print(myset)

Update a set to keep only duplicates

def main():
    myset = {"apple", "banana", "cherry"}
    myotherset = {"apple", "peach", "strawberry"}
    myset.intersection_update(myotherset)
    print(myset)

Create a set to with only duplicates

def main():
    myset = {"apple", "banana", "cherry"}
    myotherset = {"apple", "peach", "strawberry"}
    deltaset = myset.intersection(myotherset)
    print(deltaset)

Update a set to keep all non-duplicates

def main():
    myset = {"apple", "banana", "cherry"}
    myotherset = {"apple", "peach", "strawberry"}
    myset.symmetric_difference_update(myotherset)
    print(myset)

Create a set to with all non-duplicates

def main():
    myset = {"apple", "banana", "cherry"}
    myotherset = {"apple", "peach", "strawberry"}
    deleaset = myset.symmetric_difference(myotherset)
    print(deltaset)

10.4. Dictionaries

Dictionaries are used to store values in key-value pairs. As of Python 3.7 dictionaries are ordered, and earlier Python versions are unordered. Also dictionaries are changable.

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    print(mydict)

Accessing an item

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    print(mydict["john"])

Dictionaries cannot have two items with the same key:

def main():
    mydict = {
        "jack": "apple",
        "jack": "cherry",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    print(mydict)

Determine the amount of items in a dictionary

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    print(len(mydict))

Data type within Python

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    print(type(mydict))
<class 'dict'>
def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    print(mydict)

Retrieve a value based on the key

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    a = mydict["jonn"]
    print(a)

Retrieve a value based on the key with the get() method.

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    a = mydict.get("jonn")
    print(a)

Retrieve all the keys

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    b = mydict.keys()
    print(b)

Updating the dictionary will also update view on list of keys that was retrieved

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    b = mydict.keys()
    print(b)
    mydict["jane"] = "cherry"
    print(b)

Retrieve all the values

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    c = mydict.values()
    print(c)

Updating the dictionary will also update view on list of values that was retrieved

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    c = mydict.values()
    print(c)
    mydict["jim"] = "cherry"
    mydict["jane"] = "cherry"
    print(c)

Retrieve all the items

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    d = mydict.items()
    print(d)

Updating the dictionary will also update view on list of items that was retrieved

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    c = mydict.items()
    print(c)
    mydict["jim"] = "cherry"
    mydict["jane"] = "cherry"
    print(c)

Check if an item exists

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    if "james" in mydict:
        print("James exists")

Updating values and if the item doesn’t exist the item is created.

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    mydict["jim"] = "cherry"
    print(mydict)
    mydict.update({"jim", "apple"})
    print(mydict)

Removing items

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    mydict.pop("jim")
    print(mydict)
    mydict.popitem()
    print(mydict)
    del mydict["john"]
    print(mydict)
    mydict.clear()
    print(mydict)

Looping through a dictionary

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    for a in mydict:
        print(a)
    for a in mydict:
        print(mydict[a])
    for a in mydict.values():
        print(a)
    for a in mydict.keys():
        print(a)
    for a, b in mydict.items():
        print(a, b)

Copying a dictionary

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    myotherdict = mydict.copy()
    print(myotherdict)
    myotherdict = dict(mydict)
    print(myotherdict)

Make a reference of a dictionary

def main():
    mydict = {
        "jack": "apple",
        "john": "banana",
        "james": "apple"
        "jim": "banana"
    }
    myotherdict = mydict
    print(mydict)
    print(myotherdict)
    myotherdict["jane"] = "cherry"
    print(mydict)
    print(myotherdict)

Using nested dictionaries

def main():
    mydict = {
        "jack": {
            "food": "apple"
            "drink": "water"
        },
        "john": {
            "food": "banana"
            "drink": "mildk"
        }
    }
    print(mydict)
def main():
    order1 = {
        "food": "apple"
        "drink": "water"
    }
    order2 = {
        "food": "banana"
        "drink": "mildk"
    }
    mydict = {
        "jack": order1,
        "john": order2
    }
    print(mydict)

10.5. Arrays

def main():
    myarray = ["apple", "banana", "cherry"]
    print(myarray)

List length len()

def main():
    myarray = ["apple", "banana", "cherry"]
    print(len(myarray))

Looping an array

def main():
    myarray = ["apple", "banana", "cherry"]
    for a in myarray:
        print(a)

Adding an element

def main():
    myarray = ["apple", "banana", "cherry"]
    myarray.append("kiwi")
    print(myarray)

Remove the first occurrence of an element

def main():
    myarray = ["apple", "banana", "cherry", "apple"]
    myarray.remove("apple")
    print(myarray)

Remove an element of a position

def main():
    myarray = ["apple", "banana", "cherry"]
    myarray.pop(1)
    print(myarray)