Python

Intermediate Data Types

Intermediate Data Types

This tutorial covers Python intermediate data types.

It continues the previous tutorial of Python data types.

For Python data types here.

It covers some of the aspects of Python data types in more details.

  • Casting
  • Strings built-in functions
  • Numbers built-in functions
  • Collections built-in functions

Python Casting

Casting refers to the change (or converting) of one type to another.

As previously seen, casting can convert int to a float (or numbers to numbers).

# Integer to float
x = float(14)

print(x)
# The output will produce the number 14.0

Casting also works with strings.

# Integer to string
x = str(14)

print(x)
type(x)

# Output 14
# Output str (text)
# String to float
x = float("7")

print(x)
type(x)

# Output 7.0
# Output float

The process of casting can work really well with the functions “print()” and “input()”.

In “print()”, operators and commas can add items together. When combining strings together, the process refers to concatenation.

But when Python tries to concatenate a string and a number, the program raises an error. Casting can avoid this issue.

a, b = 5, 7
print(a + b)

# Output 12
a = 7
b = "Hello"
print(a + b)

# Output TypeError

Using a comma will fix the above, as Python will not try to concatenate.

a = 7
b = "Hello"
print(a, b)

# Output 7 Hello

The following is an example of the usefulness of casting.

a = 7
b = "Hello"
print("There are " + str(a) + " bears. " + b + " bears.")

# Output "There are 7 bears. Hello bears."

Spaces are important in concatenation, as the process does not add them automatically.

Python strings built-in functions

There are many built-in functions (methods) in Python. These methods come with the programming language and do not need importing.

Slicing

In Python, slicing refers to only part of the specific data type. In strings, slicing can cut partially some of the text.

Slicing works by specifying the start and end index of the slice.

Note that indexing starts from 0 and empty spaces and symbols also count.

Hi, friend!

H i ,   f r i e n d !
0 1 2 3 4 5 6 7 8 9 10

In the case of only 1 number, without a colon, Python performs indexing.

a = "This is a string"

print(a[0])

# Output "T"

The following is an example of slicing with the “print” statement.

a = "This is a string"

print(a[5:16])

# Output "is a string"
a = "This is a string"

print(a[1:16])

# Output "his is a string"

Declaring indexes is not mandatory. If not specified, slicing starts from beginning to end.

a = "This is a string"

print(a[5:])

# Output "is a string"
a = "This is a string"

print(a[:9])

# Output "This is a"
a = "This is a string"

print(a[:])

# Output "This is a string"

Split() and strip()

The “split()” method separates the text inside the string, and outputs it as a list. Inside the brackets of the function is the separator (where to split the text).

a = "This is a string"

print(a.split())

# Output: ['This', 'is', 'a', 'string']
a = "This, is a string!"

print(a.split(","))

# Output: ['This', ' is a string!']

The “strip()” function removes empty spaces either in the beginning or the end of the string.

a = "  This is a string       "

print(a.strip())

# Output: "This is a string"

Lower() and upper()

As the names suggest, lower and upper methods change the letters’ case of the text inside the string.

The “lower()” function changes all letters to lowercase.

a = "This Is A String"

print(a.lower())

# Output: "this is a string"

The “upper()” function changes all letters to uppercase.

a = "This is a string"

print(a.upper())

# Output: "THIS IS A STRING"

Python numbers built-in functions

In the programming language of Python, there are also built-in numbers methods. They are “min()”, “max()”, “pow()”, and “abs()”.

Min() and max()

As the names suggest, min and max functions output the lowest and highest number, respectively.

The method “min()” finds the lowest value between a collection of numbers.

a = [23, 12, 6, 87, 4, 54, 2, 35]
print(min(a))

# Output: 2

The method “max()” finds the highest value between a collection of numbers.

a = [23, 12, 6, 87, 4, 54, 2, 35]
print(max(a))

# Output: 87

Pow() and abs()

The function of “pow()” refers to the power of a number. There are two arguments inside the method: the base value and the exponential value.

a = pow(3, 3)
print(a)

# Output: 27

The method of “abs()” outputs the absolute value of a number. Absolute refers to a value that is always positive.

a = abs(-7.6)
print(a)

# Output: 7.6

Python collections built-in functions

This section covers indexing of collections (lists, tuples, sets, and dictionaries). In addition, it introduces some of the most common built-in functions (methods) relating to storage data types (collections).

Indexing

As mentioned previously, indexing starts from 0. Its purpose is to provide access to specific item (value) in a data type.

Below is a summary of collections’ characteristics.

python lists tuples sets dictionaries

Lists use the number of index inside square brackets.

someList = ["UK", "Canada", "Germany", "Japan"]
print(someList[2])

# Output: Germany

Using slicing to access a range of indexes. Note that the end index number does not apply.

someList = ["UK", "Canada", "Germany", "Japan"]
print(someList[0:2])

# Output: ['UK', 'Canada']

Tuples also use the number of index inside square brackets.

someTuple = ("UK", "Canada", "Germany", "Japan")
print(someTuple[1])

# Output: Canada
someTuple = ("UK", "Canada", "Germany", "Japan")
print(someTuple[1:3])

# Output: ('Canada', 'Germany')

Sets cannot be indexed. Instead, the “in” keyword can check if an item (value) is in the set. Adding the keyword “and” allows multi-checking. This also works with lists, tuples, and dictionaries.

someSet = {"UK", "Canada", "Germany", "Japan"}
print("UK" in someSet)

# Output: True
someSet = {"UK", "Canada", "Germany", "Japan"}
print("UK" and "Japan" in someSet)

# Output: True

Note that if one of the items is not present in the set, the outcome will show as False.

Dictionaries use the keys instead of the index numbers.

someDict = {
    "UK": "London",
    "Canada": "Ottawa",
    "Germany": "Berlin",
    "Japan": "Tokyo"
}

print(someDict["Canada"])

# Output: Ottawa

Adding items

In Python, each data type has a different way of adding items.

Lists can either add items at the end or throughout it. The first operates through the “append()” function and the second through the “insert() function” (through the use of indexing).

someList = ["Paris", "Budapest"]
someList.append("Oslo")

print(someList)

# Output: ['Paris', 'Budapest', 'Oslo']
someList = ["Paris", "Budapest"]
someList.insert(1, "Oslo")

print(someList)

# Output: ['Paris', 'Oslo', 'Budapest']

Tuples are immutable, therefore items inside a tuple cannot change.

Sets can add items (values) through the method “add()“.

someSet = {"Paris", "Budapest"}
someSet.add("Oslo")

print(someSet)

# Output: {'Paris', 'Oslo', 'Budapest'}

Dictionaries can add items either with the “update()” method or assigning new pair of key/value.

someDict = {
    "Paris": 105.4,
    "Budapest": 525.2
}

someDict.update({"Oslo": 454})

print(someDict)

# Output: {'Paris': 105.4, 'Budapest': 525.2, 'Oslo': 454}
someDict = {
    "Paris": 105.4,
    "Budapest": 525.2
}

someDict["Oslo"] = 454

print(someDict)

# Output: {'Paris': 105.4, 'Budapest': 525.2, 'Oslo': 454}

When the key/value pair does not exist in the dictionary, Python adds it at the end.

Removing items

Similarly to adding items, each data type has its own way of doing so.

Lists has three different ways of removing items. These are “pop()“, “remove()“, and “del“.

Without index, the pop method removes the last item in the list. With indexing, the specific items disappears.

someList = ["UK", "Canada", "Germany", "Japan"]
someList.pop(1)

print(someList)

# Output: ['UK', 'Germany', 'Japan']

The remove function deletes a specific name item.

someList = ["UK", "Canada", "Germany", "Japan"]
someList.remove("UK")

print(someList)

# Output: ['Canada', 'Germany', 'Japan']

The del method removes items through indexing. Note that without indexing, the del function deletes the whole list.

someList = ["UK", "Canada", "Germany", "Japan"]
del someList[2]

print(someList)

# Output: ['UK', 'Canada', 'Japan']
someList = ["UK", "Canada", "Germany", "Japan"]
del someList

print(someList)

# Output: NameError: name 'someList' is not defined

Tuples are immutable. therefore removing items does not apply.

Sets can delete items through three functions, and they are “discard()“, “remove()“, and “pop()“.

someSet = {"UK", "Canada", "Germany", "Japan"}
someSet.discard("Germany")

print(someSet)

# Output: {'UK', 'Canada', 'Japan'}
someSet = {"UK", "Canada", "Germany", "Japan"}
someSet.remove("Germany")

print(someSet)

# Output: {'UK', 'Canada', 'Japan'}

The pop method deletes an item randomly.

someSet = {"UK", "Canada", "Germany", "Japan"}
someSet.pop()

print(someSet)

# Output: {'Canada', 'Germany', 'Japan'}

Dictionaries also delete items through three different functions. These are “pop()“, “popitem()“, and “del“.

In dictionaries, the “pop()” method requires the key name in order to remove an item.

someDict = {
    "UK": "London",
    "Canada": "Ottawa",
    "Germany": "Berlin",
    "Japan": "Tokyo"
}

someDict.pop("Japan")
print(someDict)

# Output: {'UK': 'London', 'Canada': 'Ottawa', 'Germany': 'Berlin'}

The “popitem()” function removes the last item in the dictionary.

someDict = {
    "UK": "London",
    "Canada": "Ottawa",
    "Germany": "Berlin",
    "Japan": "Tokyo"
}

someDict.popitem()
print(someDict)

# Output: {'UK': 'London', 'Canada': 'Ottawa', 'Germany': 'Berlin'}

The “del” function in dictionaries remove items through the key names. Note that without a key name, the del function deletes the whole dictionary.

someDict = {
    "UK": "London",
    "Canada": "Ottawa",
    "Germany": "Berlin",
    "Japan": "Tokyo"
}

del someDict["Canada"]
print(someDict)

# Output: {'UK': 'London', 'Germany': 'Berlin', 'Japan': 'Tokyo'}
someDict = {
    "UK": "London",
    "Canada": "Ottawa",
    "Germany": "Berlin",
    "Japan": "Tokyo"
}

del someDict
print(someDict)

# Output: NameError: name 'someDict' is not defined

Changing items

Replacing (or changing) items operates differently depending on the data type.

Lists changes items by assigning new values through indexing and slicing.

someList = ["Paris", "Budapest", "Oslo"]
someList[0] = "London"

print(someList)

# Output: ['London', 'Budapest', 'Oslo']
someList = ["Paris", "Budapest", "Oslo"]
someList[0:2] = ["London", "Sofia"]

print(someList)

# Output: ['London', 'Sofia', 'Oslo']

Tuples are immutable, so changing items does not apply.

Sets do not allow changing items.

Dictionaries allow changing items through two methods, new key/value pair and “update()“.

someDict = {
    "Revenue": "58m",
    "Year": 2023,
    "Employees": 268
}

someDict["Revenue"] = "41m"
print(someDict)

# Output: {'Revenue': '41m', 'Year': 2023, 'Employees': 268}
someDict = {
    "Revenue": "58m",
    "Year": 2023,
    "Employees": 268
}

someDict.update({"Employees": 240})
print(someDict)

# Output: {'Revenue': '58m', 'Year': 2023, 'Employees': 240}

Sort(), len() and count()

The function of “sort()” provides sorting operations. “Len()” counts the number of items inside a data type and outputs the total. And the method of “count()”, counts the number of specific item inside a data type.

Sort()

The function of “sort()” is exclusive only to lists. By default, sort will arrange the items in ascending order. For example (0, 1, 2, 3, etc.) or alphabetically (a, b, c, d, etc.).

someList = ["UK", "Canada", "Germany", "Japan"]
someList.sort()

print(someList)

# Output: ['Canada', 'Germany', 'Japan', 'UK']
someList = [4, 7, 23, 1, 15, 22]
someList.sort()

print(someList)

# Output: [1, 4, 7, 15, 22, 23]

Len()

The method of “len()” returns the number of items in a data type. Note that in a string the function returns the number of characters and in dictionaries the number of pairs.

someList = ["UK", "Canada", "Germany", "Japan"]
print(len(someList))

# Output: 4
someSet = {"UK", "Canada", "Germany", "Japan"}
print(len(someSet))

# Output: 4
string = "This is a string"
print(len(string))

# Output: 16
someDict = {
    "Revenue": "58m",
    "Year": 2023,
    "Employees": 268
}

print(len(someDict))

# Output: 3

Count()

The method of “count()” return the number of specific items in a data type. Counting can only operate with lists, tuples, and strings.

someList = ["UK", "Canada", "Germany", "UK"]
print(someList.count("UK"))

# Output: 2
someTuple = ("UK", "Canada", "Germany", "UK")
print(someTuple.count("Canada"))

# Output: 1
string = "This is a string"
print(string.count("i"))

# Output: 3

Next: Python Intermediate Conditions