Manipulate Various Built-in Python Objects

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to manipulate various built-in Python objects. Python offers a range of built-in data types such as numbers, strings, lists, and dictionaries. Mastering these objects is crucial for every Python programmer.

In addition, through hands - on exercises, you will practice essential Python operations and learn how to work effectively with Python numbers, strings, lists, and dictionaries.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 85% completion rate. It has received a 99% positive review rate from learners.

Working with Python Numbers

Python offers robust support for numerical operations. In programming, numbers are fundamental data types used for calculations and representing quantities. This step will introduce you to basic number manipulation in Python, which is essential for performing various mathematical operations in your programs.

Basic Arithmetic Operations

To start working with Python numbers, you first need to open a Python interactive shell. You can do this by typing python3 in your terminal. The Python interactive shell allows you to write and execute Python code line by line, which is great for testing and learning.

python3

Once you're in the Python interactive shell, you can try some basic arithmetic operations. Python follows the standard mathematical rules for arithmetic, such as the order of operations (PEMDAS: Parentheses, Exponents, Multiplication and Division, Addition and Subtraction).

>>> 3 + 4*5    ## Multiplication has higher precedence than addition, so 4*5 is calculated first, then added to 3
23
>>> 23.45 / 1e-02    ## Scientific notation for 0.01 is used here. Division is performed to get the result
2345.0

Integer Division

Python 3 handles division differently from Python 2. Understanding these differences is crucial to avoid unexpected results in your code.

>>> 7 / 4    ## In Python 3, regular division returns a float, even if the result could be an integer
1.75
>>> 7 // 4   ## Floor division (truncates the decimal part) gives you the quotient as an integer
1

Number Methods

Numbers in Python have several useful methods that are often overlooked. These methods can simplify complex numerical operations and conversions. Let's explore some of them:

>>> x = 1172.5
>>> x.as_integer_ratio()    ## This method represents the float as a fraction, which can be useful for some mathematical calculations
(2345, 2)
>>> x.is_integer()    ## Checks if the float is an integer value. In this case, 1172.5 is not an integer, so it returns False
False

>>> y = 12345
>>> y.numerator    ## For integers, the numerator is the number itself
12345
>>> y.denominator    ## For integers, the denominator is always 1
1
>>> y.bit_length()    ## This method tells you the number of bits required to represent the number in binary, which can be useful in bitwise operations
14

These methods are particularly useful when you need to perform specific numerical operations or conversions. They can save you time and make your code more efficient.

When you're done exploring the Python interactive shell, you can exit it by typing:

>>> exit()

Working with Python Strings

Strings are one of the most commonly used data types in Python. They are used to represent text and can contain letters, numbers, and symbols. In this step, we'll explore various string operations, which are essential skills for working with text data in Python.

Creating and Defining Strings

To start working with strings in Python, we first need to open a Python interactive shell. This shell allows us to write and execute Python code line by line, which is great for learning and testing. Open a Python interactive shell again using the following command:

python3

Once the shell is open, we can define a string. In this example, we'll create a string that contains stock ticker symbols. A string in Python can be defined by enclosing text within single quotes (') or double quotes ("). Here's how we define our string:

>>> symbols = 'AAPL IBM MSFT YHOO SCO'
>>> symbols
'AAPL IBM MSFT YHOO SCO'

We've now created a string variable named symbols and assigned it a value. When we type the variable name and press enter, Python displays the value of the string.

Accessing Characters and Substrings

In Python, strings can be indexed to access individual characters. Indexing starts at 0, which means the first character of a string has an index of 0, the second has an index of 1, and so on. Negative indexing is also supported, where -1 refers to the last character, -2 refers to the second last character, and so on.

Let's see how we can access individual characters in our symbols string:

>>> symbols[0]    ## First character
'A'
>>> symbols[1]    ## Second character
'A'
>>> symbols[2]    ## Third character
'P'
>>> symbols[-1]   ## Last character
'O'
>>> symbols[-2]   ## Second to last character
'C'

We can also extract substrings using slicing. Slicing allows us to get a part of the string by specifying a start and an end index. The syntax for slicing is string[start:end], where the substring includes characters from the start index up to (but not including) the end index.

>>> symbols[:4]    ## First 4 characters
'AAPL'
>>> symbols[-3:]   ## Last 3 characters
'SCO'
>>> symbols[5:8]   ## Characters from index 5 to 7
'IBM'

String Immutability

Strings in Python are immutable, which means once a string is created, you cannot change its individual characters. If you try to modify a character in a string, Python will raise an error.

Let's try to change the first character of our symbols string:

>>> symbols[0] = 'a'    ## This will cause an error

You should see an error like this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

This error indicates that we cannot assign a new value to an individual character in a string because strings are immutable.

String Concatenation

Although we cannot modify strings directly, we can create new strings through concatenation. Concatenation means joining two or more strings together. In Python, we can use the + operator to concatenate strings.

>>> symbols += ' GOOG'    ## Append a new symbol
>>> symbols
'AAPL IBM MSFT YHOO SCO GOOG'

>>> symbols = 'HPQ ' + symbols    ## Prepend a new symbol
>>> symbols
'HPQ AAPL IBM MSFT YHOO SCO GOOG'

It's important to remember that these operations create new strings rather than modifying the original string. The original string remains unchanged, and a new string is created with the combined value.

Testing for Substrings

To check if a substring exists within a string, we can use the in operator. The in operator returns True if the substring is found in the string and False otherwise.

>>> 'IBM' in symbols
True
>>> 'AA' in symbols
True
>>> 'CAT' in symbols
False

Notice that 'AA' returns True because it's found within "AAPL". This is a useful way to search for specific text within a larger string.

String Methods

Python strings come with numerous built-in methods that allow us to perform various operations on strings. These methods are functions that are associated with the string object and can be called using the dot notation (string.method()).

>>> symbols.lower()    ## Convert to lowercase
'hpq aapl ibm msft yhoo sco goog'

>>> symbols    ## Original string remains unchanged
'HPQ AAPL IBM MSFT YHOO SCO GOOG'

>>> lowersyms = symbols.lower()    ## Save the result to a new variable
>>> lowersyms
'hpq aapl ibm msft yhoo sco goog'

>>> symbols.find('MSFT')    ## Find the starting index of a substring
13
>>> symbols[13:17]    ## Verify the substring at that position
'MSFT'

>>> symbols = symbols.replace('SCO','')    ## Replace a substring
>>> symbols
'HPQ AAPL IBM MSFT YHOO  GOOG'

When you're done experimenting, you can exit the Python shell using the following command:

>>> exit()

Working with Python Lists

Lists are a type of data structure in Python. A data structure is a way to organize and store data so that it can be used efficiently. Lists are very versatile because they can store different types of items, like numbers, strings, or even other lists. In this step, we'll learn how to perform various operations on lists.

Creating Lists from Strings

To start working with Python lists, we first need to open a Python interactive session. This is like a special environment where we can write and run Python code right away. To start this session, type the following command in your terminal:

python3

Once you're in the Python interactive session, we'll create a list from a string. A string is just a sequence of characters. We'll define a string that contains some stock symbols separated by spaces. Then, we'll convert this string into a list. Each stock symbol will become an element in the list.

>>> symbols = 'HPQ AAPL IBM MSFT YHOO GOOG'
>>> symlist = symbols.split()    ## Split the string on whitespace
>>> symlist
['HPQ', 'AAPL', 'IBM', 'MSFT', 'YHOO', 'GOOG']

The split() method is used to break the string into parts wherever there is a whitespace. Each part then becomes an element in the new list.

Accessing and Modifying List Elements

Just like strings, lists support indexing. Indexing means we can access individual elements in the list by their position. In Python, the first element in a list has an index of 0, the second has an index of 1, and so on. We can also use negative indexing to access elements from the end of the list. The last element has an index of -1, the second last has an index of -2, and so on.

Unlike strings, list elements can be modified. This means we can change the value of an element in the list.

>>> symlist[0]    ## First element
'HPQ'
>>> symlist[1]    ## Second element
'AAPL'
>>> symlist[-1]   ## Last element
'GOOG'
>>> symlist[-2]   ## Second to last element
'YHOO'

>>> symlist[2] = 'AIG'    ## Replace the third element
>>> symlist
['HPQ', 'AAPL', 'AIG', 'MSFT', 'YHOO', 'GOOG']

Iterating Through Lists

Often, we need to perform the same operation on each element in a list. We can use a for loop to do this. A for loop allows us to go through each element in the list one by one and perform a specific action on it.

>>> for s in symlist:
...     print('s =', s)
...

When you run this code, you'll see each element in the list printed out with the label s =.

s = HPQ
s = AAPL
s = AIG
s = MSFT
s = YHOO
s = GOOG

Checking Membership

Sometimes, we need to check if a particular item exists in a list. We can use the in operator to do this. The in operator returns True if the item is in the list and False if it's not.

>>> 'AIG' in symlist
True
>>> 'AA' in symlist
False
>>> 'CAT' in symlist
False

Adding and Removing Elements

Lists have built - in methods that allow us to add and remove elements. The append() method adds an element to the end of the list. The insert() method inserts an element at a specific position in the list. The remove() method removes an element from the list by its value.

>>> symlist.append('RHT')    ## Add an element to the end
>>> symlist
['HPQ', 'AAPL', 'AIG', 'MSFT', 'YHOO', 'GOOG', 'RHT']

>>> symlist.insert(1, 'AA')    ## Insert at specific position
>>> symlist
['HPQ', 'AA', 'AAPL', 'AIG', 'MSFT', 'YHOO', 'GOOG', 'RHT']

>>> symlist.remove('MSFT')    ## Remove by value
>>> symlist
['HPQ', 'AA', 'AAPL', 'AIG', 'YHOO', 'GOOG', 'RHT']

If you try to remove an element that doesn't exist in the list, Python will raise an error.

>>> symlist.remove('MSFT')

You'll see an error message like this:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

We can also find the position of an element in the list using the index() method.

>>> symlist.index('YHOO')
4
>>> symlist[4]    ## Verify the element at that position
'YHOO'

Sorting Lists

Lists can be sorted in place, which means the original list is modified. We can sort a list alphabetically or in reverse order.

>>> symlist.sort()    ## Sort alphabetically
>>> symlist
['AA', 'AAPL', 'AIG', 'GOOG', 'HPQ', 'RHT', 'YHOO']

>>> symlist.sort(reverse=True)    ## Sort in reverse
>>> symlist
['YHOO', 'RHT', 'HPQ', 'GOOG', 'AIG', 'AAPL', 'AA']

Nested Lists

Lists can contain any type of object, including other lists. This is called a nested list.

>>> nums = [101, 102, 103]
>>> items = [symlist, nums]
>>> items
[['YHOO', 'RHT', 'HPQ', 'GOOG', 'AIG', 'AAPL', 'AA'], [101, 102, 103]]

To access elements in a nested list, we use multiple indices. The first index selects the outer list element, and the second index selects the inner list element.

>>> items[0]    ## First element (the symlist)
['YHOO', 'RHT', 'HPQ', 'GOOG', 'AIG', 'AAPL', 'AA']
>>> items[0][1]    ## Second element in symlist
'RHT'
>>> items[0][1][2]    ## Third character in 'RHT'
'T'
>>> items[1]    ## Second element (the nums list)
[101, 102, 103]
>>> items[1][1]    ## Second element in nums
102

When you're done working in the Python interactive session, you can exit it by typing:

>>> exit()

Working with Python Dictionaries

In Python, dictionaries are a fundamental data structure. They are key - value stores, which means they allow you to map one value (the value) to another (the key). This is extremely useful when dealing with data that has natural key - value relationships. For example, you might want to map a person's name (the key) to their age (the value), or as we'll see in this lab, map stock symbols (keys) to their prices (values).

Creating and Accessing Dictionaries

Let's start by opening a new Python interactive session. This is like entering a special environment where you can write and run Python code line by line. To start this session, open your terminal and type the following command:

python3

Once you're in the Python interactive session, you can create a dictionary. In our case, we'll create a dictionary that maps stock symbols to their prices. Here's how you do it:

>>> prices = {'IBM': 91.1, 'GOOG': 490.1, 'AAPL': 312.23}
>>> prices
{'IBM': 91.1, 'GOOG': 490.1, 'AAPL': 312.23}

In the first line, we're creating a dictionary named prices and assigning it some key - value pairs. The keys are the stock symbols (IBM, GOOG, AAPL), and the values are the corresponding prices. The second line just shows us the contents of the prices dictionary.

Now, let's see how to access and modify the values in the dictionary using the keys.

>>> prices['IBM']    ## Access the value for key 'IBM'
91.1

>>> prices['IBM'] = 123.45    ## Update an existing value
>>> prices
{'IBM': 123.45, 'GOOG': 490.1, 'AAPL': 312.23}

>>> prices['HPQ'] = 26.15    ## Add a new key - value pair
>>> prices
{'IBM': 123.45, 'GOOG': 490.1, 'AAPL': 312.23, 'HPQ': 26.15}

In the first line, we're accessing the value associated with the key IBM. In the second and third lines, we're updating the value for the key IBM and then adding a new key - value pair (HPQ with a price of 26.15).

Getting Dictionary Keys

Sometimes, you might want to get a list of all the keys in a dictionary. There are a couple of ways to do this.

>>> list(prices)    ## Convert dictionary keys to a list
['IBM', 'GOOG', 'AAPL', 'HPQ']

Here, we're using the list() function to convert the keys of the prices dictionary into a list.

You can also use the keys() method, which returns a special object called dict_keys.

>>> prices.keys()    ## Returns a dict_keys object
dict_keys(['IBM', 'GOOG', 'AAPL', 'HPQ'])

Getting Dictionary Values

Similarly, you might want to get all the values in a dictionary. You can use the values() method for this.

>>> prices.values()    ## Returns a dict_values object
dict_values([123.45, 490.1, 312.23, 26.15])

This method returns a dict_values object that contains all the values in the prices dictionary.

Deleting Items

If you want to remove a key - value pair from a dictionary, you can use the del keyword.

>>> del prices['AAPL']    ## Delete the 'AAPL' entry
>>> prices
{'IBM': 123.45, 'GOOG': 490.1, 'HPQ': 26.15}

Here, we're deleting the key - value pair with the key AAPL from the prices dictionary.

Checking if a Key Exists

To check if a key exists in a dictionary, you can use the in operator.

>>> 'IBM' in prices
True
>>> 'AAPL' in prices
False

The in operator returns True if the key exists in the dictionary and False otherwise.

Dictionary Methods

Dictionaries have several useful methods. Let's look at a couple of them.

>>> prices.get('MSFT', 0)    ## Get value or default if key doesn't exist
0
>>> prices.get('IBM', 0)
123.45

>>> prices.update({'MSFT': 25.0, 'GOOG': 500.0})    ## Update multiple values
>>> prices
{'IBM': 123.45, 'GOOG': 500.0, 'HPQ': 26.15, 'MSFT': 25.0}

The get() method tries to get the value associated with a key. If the key doesn't exist, it returns a default value (in this case, 0). The update() method is used to update multiple key - value pairs in the dictionary at once.

When you're done working in the Python interactive session, you can exit it by typing:

>>> exit()

Summary

In this lab, you have learned how to work with various Python built-in objects. Specifically, you've mastered operations on Python numbers and their methods, manipulated strings through indexing, slicing, and built-in functions, created and modified lists including sorting and handling nested structures, and used dictionaries for key-value storage and retrieval.

These fundamental skills are the cornerstone of more advanced Python programming. Regular practice of these operations will enhance your familiarity with Python's built-in data types.