Skip to content
Home » Google Career Certificates » Google IT Automation with Python Professional Certificate » Crash Course on Python » Week 4: Strings, Lists and Dictionaries

Week 4: Strings, Lists and Dictionaries

In this module you’ll dive into more advanced ways to manipulate strings using indexing, slicing, and advanced formatting. You’ll also explore the more advanced data types: lists, tuples, and dictionaries. You’ll learn to store, reference, and manipulate data in these structures, as well as combine them to store complex data structures.

Learning Objectives

  • Manipulate strings using indexing, slicing, and formatting
  • Use lists and tuples to store, reference, and manipulate data
  • Leverage dictionaries to store more complex data, reference data by keys, and manipulate data stored
  • Combine the String, List, and Dictionary data types to construct complex data structures

Strings


Video: Basic Structures Introduction

This video is an introduction to the next module of the course, which will cover data types and data structures in Python. Specifically, the module will cover strings, lists, and dictionaries.

What are data types and data structures?

Data types are used to represent different types of data, such as numbers, text, and images. Data structures are used to organize data in a specific way, such as lists, queues, and trees.

Why are data types and data structures important?

Data types and data structures are important because they allow us to write more efficient and robust code. By using the right data type and data structure for a given task, we can avoid errors and make our code easier to read and maintain.

What will be covered in the next module?

The next module will cover the following topics:

  • Strings: Strings are used to represent text data. In this module, we will learn how to create and manipulate strings, as well as how to perform common string operations such as searching, replacing, and splitting.
  • Lists: Lists are used to store a collection of items in a specific order. In this module, we will learn how to create and manage lists, as well as how to perform common list operations such as adding, removing, and searching.
  • Dictionaries: Dictionaries are used to store a collection of key-value pairs. In this module, we will learn how to create and manage dictionaries, as well as how to perform common dictionary operations such as adding, removing, and searching.

Conclusion:

Data types and data structures are an essential part of Python programming. By understanding the different types of data types and data structures available, and how to use them effectively, you can write more efficient and robust code.

Basic Structures Introduction in Python

Python is a general-purpose programming language that is known for its simplicity and readability. It is a popular choice for beginners and experienced programmers alike.

One of the things that makes Python so easy to learn is its use of data structures. Data structures are ways of organizing data so that it can be accessed and manipulated efficiently. Python has a number of built-in data structures, including:

  • Lists: Lists are mutable sequences of objects. They can be used to store any type of data, and can be resized as needed.
  • Tuples: Tuples are immutable sequences of objects. They are similar to lists, but cannot be resized.
  • Sets: Sets are unordered collections of unique objects. They can be used to remove duplicates from a list, or to find the intersection or union of two sets.
  • Dictionaries: Dictionaries are mutable mappings of keys to values. They can be used to store any type of data, and can be accessed using the keys.

In this tutorial, we will introduce the basic concepts of these data structures and show how to use them in Python.

Lists

Lists are created using square brackets ([]). To add an element to a list, use the append() method. To remove an element from a list, use the remove() method. To access an element in a list, use the [] operator.

For example, the following code creates a list of numbers and then prints the first element in the list:

my_list = [1, 2, 3, 4, 5]
print(my_list[0])

Output:

1

You can also use the for loop to iterate over the elements in a list:

for number in my_list:
    print(number)

Output:

1
2
3
4
5

Tuples

Tuples are created using parentheses (()). To access an element in a tuple, use the [] operator.

For example, the following code creates a tuple of colors and then prints the first element in the tuple:

my_tuple = ("red", "green", "blue")
print(my_tuple[0])

Output:

red

You can also use the for loop to iterate over the elements in a tuple:

for color in my_tuple:
    print(color)

Output:

red
green
blue

Sets

Sets are created using curly braces ({}). To add an element to a set, use the add() method. To remove an element from a set, use the remove() method. To check if an element is in a set, use the in operator.

For example, the following code creates a set of numbers and then prints whether the number 5 is in the set:

my_set = {1, 2, 3, 4, 5}
print(5 in my_set)

Output:

True

You can also use the for loop to iterate over the elements in a set:

for number in my_set:
    print(number)

Output:

1
2
3
4
5

Dictionaries

Dictionaries are created using curly braces ({}) and colons (:) to separate the keys from the values. To add an element to a dictionary, use the [] operator and assign a value to the key. To access an element in a dictionary, use the [] operator and pass in the key.

For example, the following code creates a dictionary of colors and their corresponding hex codes and then prints the hex code for the color red:

my_dictionary = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}
print(my_dictionary["red"])

Output:

#FF0000

You can also use the for loop to iterate over the items in a dictionary:

for color, hex_code in my_dictionary.items():
    print(color, hex_code)

Output:

red #FF0000
green #00FF00
blue #0000FF

These are just a few of the built-in data structures in Python. There are many other data structures available, but these are the most common and useful for beginners to learn.

Welcome back and congratulations
on getting this far. I sure am glad we
didn’t lose you and all those loops we covered
in the last module. You’re doing great and
making tons of progress. In earlier videos, we covered the basic elements
of Python syntax. We talked about how
to define functions, how to make your computer act differently based
on conditionals, and how to make it perform operations repeatedly
using while, and for loops, and recursion. Now that we have the basics
of syntax out of the way, we can start growing our Python
knowledge which will let us do more and more
interesting operations. Remember, one of our main goals in this course is to help you learn to write short
Python scripts that automate actions, you’ve made big steps
towards getting there. In the upcoming videos, we’re going to learn a bunch of new super useful skills to add to your
programming toolbox. We’ll check out some
data types provided by the Python language to help us solve common problems
with our scripts. In particular, we’ll
do a deep dive into strings, lists,
and dictionaries. Heads-up, while we’ve used strings in our scripts already, we barely scratched
the surface of all the things we can
do with them in Python. We also ran into a few lists in some examples but there’s a lot more of them we haven’t seen yet. Dictionaries are a
whole new data type for us to dig our teeth into. These are all data types or data structures that
are super flexible. We’re going to use them to write all kinds of scripts in Python. So it’s a good idea to spend some time getting to know them, and learning when to use them, and how to make the
most out of them. We’ve got a lot of new and
exciting concepts to discover. So let’s get right to it.

Video: What is a string?

This video provides an overview of strings in Python, including their definition, syntax, and common operations.

What are strings?

Strings are a data type in Python that represent text data. They are written between quotes, either double quotes or single quotes.

Common string operations:

Some common string operations include:

  • Concatenation: Using the plus sign (+) to combine two or more strings into a single string.
  • Multiplication: Multiplying a string by a number to repeat the string that many times.
  • Length: Using the len() function to get the number of characters in a string.
  • Accessing parts of a string: Using square brackets ([]) to access individual characters or slices of a string.
  • Modifying strings: Using various string methods to change the contents of a string.

Examples of using strings in scripts:

  • Checking if files are named a certain way
  • Creating a list of emails
  • Working with different actions according to the name of each file
  • Changing the default values for configuration options

Conclusion:

Strings are a versatile and powerful data type in Python. By understanding the common string operations and how to use them effectively, you can write more efficient and robust code.

In the next few videos, the course will cover some of the specific string operations that are available in Python, including how to access and modify strings.

What is a string?

A string in Python is a sequence of characters. Strings are written between quotes, either double quotes or single quotes. For example, the following are all strings:

"Hello, world!"
'This is a string.'
"This is also a string."

Strings can be used to represent a variety of data, such as usernames, email addresses, and file names. They can also be used to store text for display to the user or for writing to a file.

String operations

There are a number of operations that can be performed on strings in Python. Some of the most common include:

  • Concatenation: Concatenation is the process of joining two or more strings together. This can be done using the plus sign (+). For example, the following code concatenates the strings "Hello", ,, and "world!" to create a new string:
>>> "Hello" + ", " + "world!"
'Hello, world!'
  • Indexing: Indexing is the process of accessing a specific character in a string. This can be done using square brackets ([]). For example, the following code accesses the first character in the string "Hello, world!":
>>> "Hello, world!"[0]
'H'
  • Slicing: Slicing is the process of extracting a substring from a string. This can be done using square brackets ([]) and a colon (:). For example, the following code extracts the substring "world" from the string "Hello, world!":
>>> "Hello, world!"[6:]
'world'
  • Searching: Strings can be searched for specific patterns using the find() and in operators. For example, the following code searches the string "Hello, world!" for the substring "world":
>>> "Hello, world!".find("world")
6

String methods

Strings also have a number of methods that can be used to perform various operations on them. Some of the most common include:

  • upper(): This method converts the string to uppercase.
  • lower(): This method converts the string to lowercase.
  • strip(): This method removes whitespace from the beginning and end of the string.
  • split(): This method splits the string into a list of strings, based on a specified delimiter.
  • join(): This method joins a list of strings into a single string, using a specified delimiter.

Conclusion

Strings are a powerful data type in Python that can be used to represent and manipulate text data. By understanding the various operations and methods that can be performed on strings, you can write more efficient and effective Python code.

By now, we’ve used strings
in a lot of examples, but we haven’t spent time
looking at them in detail yet. Before we dive into the
nitty-gritty though, let’s go over what we’ve seen so far and add a few more points. First, a quick refresher. A string is a data type in Python that’s used to represent
a piece of text. It’s written between quotes, either double quotes or
single quotes, your choice. It doesn’t matter which
type of quotes you use as long as they match. If we mix up double
and single quotes, Python won’t be too happy, and it’ll return a syntax error, telling us it couldn’t find
the end of the string. A string can be as short
as zero characters, usually called an empty
string or really long. We also learned that we
can use strings to build longer strings
using the plus sign and action called concatenating. A less common operation is to multiply the string by a number, which multiplies the content of the string that many
times like this. If we want to know
how long a string is, we can use the len function which we saw in earlier videos. The len function tells us the number of characters
contained in the string. We can use strings to represent a lot of
different things. They can hold a username, the name of a machine, an email address,
the name of a file, and any other text. A lot of the data that we’ll interact with will be
stored in strings, so it’s important to
know how to use them. There are tons of things we could do with strings in our scripts. For example, we can check if files are
named a certain way by looking at the filename and seeing if they
match our criteria, or we can create a list
of emails by checking out the users of our system
and concatenating our domain. I recently wrote a script that worked with a bunch of files and took different actions according to the
name of each file. So the file ended in a
certain extension say, .TXT , then my script would print it. If the file had a certain
string and the name, say, test, then my script would ignore it and move on
to the next thing and so on. The contents of a text
file are also strings. A few months ago, I had to
change the default values for a bunch of configuration
options from true to false. So I wrote a function that
would find the string true in a file and
replace it with false. You can probably think
of more examples where your code needs to
handle strings, but to use strings effectively, we need to know what options are available to us in Python. In the next few videos, we’ll cover some
of the operations we can perform over strings, including how to access parts
of them and modify them.

Video: The Parts of a String

String indexing is a way to access specific characters or groups of characters in a string. Python strings are indexed starting at 0, so the first character in a string is at index 0, the second character is at index 1, and so on.

To access a single character in a string, use square brackets ([]) and the index of the character you want to access. For example, the following code returns the second character in the string "Hello, world!":

"Hello, world!"[1]

Output:

e

To access a slice of a string, use square brackets ([]) and a colon (:). The range of the slice is specified by two indexes, separated by the colon. The first index is the starting index, and the second index is the ending index. The ending index is not included in the slice.

For example, the following code returns the substring "world" from the string "Hello, world!":

"Hello, world!"[6:]

Output:

world

You can also use negative indexes to access characters in a string, starting from the back of the string. For example, the following code returns the last character in the string "Hello, world!":

"Hello, world!"[-1]

Output:

!

String indexing is a powerful tool that can be used for a variety of tasks, such as extracting substrings from strings, formatting strings, and validating user input.

The Parts of a String in Python

A string in Python is a sequence of characters. Strings are written between quotes, either double quotes or single quotes. For example, the following are all strings:

"Hello, world!"
'This is a string.'
"This is also a string."

Strings can be used to represent a variety of data, such as usernames, email addresses, and file names. They can also be used to store text for display to the user or for writing to a file.

Parts of a string

A string can be divided into the following parts:

  • Characters: A character is a single symbol in a string. For example, the string "Hello, world!" contains 13 characters.
  • Substrings: A substring is a sequence of characters within a string. For example, the substring "world" is contained in the string "Hello, world!".
  • Indices: An index is a number that represents the position of a character in a string. Indices start at 0, so the first character in a string has index 0, the second character has index 1, and so on.

Accessing parts of a string

To access a specific part of a string, you can use the following methods:

  • Indexing: To access a single character in a string, you can use square brackets ([]) and the index of the character you want to access. For example, the following code returns the second character in the string "Hello, world!":
"Hello, world!"[1]

Output:

e
  • Slicing: To access a substring in a string, you can use square brackets ([]) and a colon (:). The range of the substring is specified by two indexes, separated by the colon. The first index is the starting index, and the second index is the ending index. The ending index is not included in the slice.

For example, the following code returns the substring "world" from the string "Hello, world!":

"Hello, world!"[6:]

Output:

world

You can also use negative indexes to access characters in a string, starting from the back of the string. For example, the following code returns the last character in the string "Hello, world!":

"Hello, world!"[-1]

Output:

!

Modifying parts of a string

You can modify parts of a string using the following methods:

  • Assignment: To assign a new value to a character in a string, you can use square brackets ([]) and the index of the character you want to modify. For example, the following code replaces the second character in the string "Hello, world!" with the letter “e”:
"Hello, world!"[1] = "e"

Output:

Heee, world!
  • Slicing: To replace a substring in a string with a new string, you can use square brackets ([]) and a colon (:). The range of the substring to be replaced is specified by two indexes, separated by the colon. The first index is the starting index, and the second index is the ending index. The ending index is not included in the slice.

For example, the following code replaces the substring "world" in the string "Hello, world!" with the string “Python”:

"Hello, world!"[6:] = "Python"

Output:

Hello, Python!

Conclusion

By understanding the parts of a string and how to access and modify them, you can write more efficient and effective Python code.

[MUSIC] When we first came across the for loop, we called out that we can iterate
over a string character by character. But what if we want to access just
a specific character or characters? We might want to do this, for example,
if we have a text that’s too long to display and
we want to show just a portion of it. Or if we want to make an acronym by taking
the first letter of each word in a phrase. We can do that through an operation
called string indexing. This operation lets us access
the character in a given position or index using square brackets and
the number of the position we want. Like this. This might seem confusing at first,
like Python is acting up. We’re asking for the first character,
and it’s giving us the second. What gives Python? Well, what’s happening here is that Python
starts counting indexes from 0 not 1. Just like it does with the range function. So if we want the first character,
we need to access the one at index 0. Knowing that indexes start at 0, which one do you think will be
the last index in the string? It’ll always be one less than
the length of the string. In this case, our string has six
characters, so the last index will be 5. Let’s try it out. We see that the character in position
five is the last character of the string. And if we try to access index six, we get an index error telling
us that it’s out of range. We can only go up to length minus 1. What if you want to print the last
character of a string but you don’t know how long it is? You can do that using negative indexes. Let’s see that in a different example. In this example, we don’t know the length
of the string, but it doesn’t matter. Using negative indexes lets us access
the positions in the string starting from the last. Nice, right? On top of accessing individual characters,
we can also access a slice of a string. A slice is the portion of a string that
can contain more than one character, also sometimes called a substring. We do that by creating a range
using a colon as a separator. Let’s see an example of this. The range we use when accessing a slice of
a string works just like the one created by the range function. It includes the first number, but
goes up to one less than the last number. In this case, we start with indexed one,
the second letter of the string, and go up to index three,
the fourth letter of the string. Another option for the range is to
include only one of the two indexes. In that case, it’s assumed that the other
index is either 0 for the first value or the length of the string for
the second value. Check this out. Accessing the slice from nothing
to 4 takes the first four characters of the string, indexes 0 to 3. Accessing the slice from 4 to nothing
takes everything from index four onward. All of this indexing might
seem confusing at first. Don’t worry, we all took time
to wrap our heads around it. Just like all the challenges
we’ve come across so far, the key is to keep practicing
until you master it. And there are a bunch of exercises
ahead to help you with that. Now that we know how to select, slice, and
access the parts of the string we want, we’re going to learn how to modify them. That’s coming up next.

Reading: String Indexing and Slicing

Reading

Video: Creating New Strings

Strings in Python are immutable, which means that they can’t be changed. To modify a string, you need to create a new string based on the old one.

There are two ways to do this:

  1. Use string concatenation: You can use the plus sign (+) to combine two or more strings into a single string.
  2. Use string methods: There are a number of string methods that can be used to modify strings, such as the replace() method.

Example of using string concatenation to modify a string:

message = "This is a message."

# Create a new string by concatenating the old string with the new text.
new_message = message + " I'm adding new text."

# Print the new string.
print(new_message)

Output:

This is a message. I'm adding new text.

Example of using a string method to modify a string:

message = "I love Python!"

# Replace the word "Python" with the word "JavaScript".
new_message = message.replace("Python", "JavaScript")

# Print the new string.
print(new_message)

Output:

I love JavaScript!

Example of a function to replace the domain in an email address:

def replace_domain(email_address, old_domain, new_domain):
  """Replaces the old domain in an email address with the new domain.

  Args:
    email_address: The email address to be checked.
    old_domain: The old domain to be replaced.
    new_domain: The new domain to replace the old domain with.

  Returns:
    The updated email address, or the original email address if the old domain
    was not found.
  """

  # Check if the old domain is contained in the email address.
  if "@{}".format(old_domain) in email_address:
    # Find the index where the old domain starts.
    index = email_address.find("@{}".format(old_domain))

    # Create the new email address.
    new_email = email_address[:index] + "@{}".format(new_domain) + email_address[index+len("@{}".format(old_domain)):]

    # Return the new email address.
    return new_email
  else:
    # The old domain was not found, so return the original email address.
    return email_address

# Example usage:

email_address = "john.doe@example.com"
new_email = replace_domain(email_address, "example.com", "google.com")

print(new_email)

Output:

john.doe@google.com

Conclusion:

By understanding the different ways to modify strings in Python, you can write more efficient and robust code.

Creating New Strings in Python

There are two main ways to create new strings in Python:

  1. Using string literals: String literals are sequences of characters enclosed in single (') or double (") quotes. For example, the following are all string literals:
"Hello, world!"
'This is a string literal.'
"""This is a multiline string literal."""
  1. Using string concatenation: String concatenation is the process of combining two or more strings into a single string. The + operator is used to concatenate strings. For example:
first_name = "John"
last_name = "Doe"

full_name = first_name + " " + last_name

print(full_name)

Output:

John Doe

In addition to these two methods, there are a number of built-in string functions that can be used to create new strings. For example, the str() function can be used to convert any object to a string. The join() method can be used to join a list of strings into a single string, separated by a specified character.

Here are some examples of using built-in string functions to create new strings:

# Convert a number to a string.
number = 123
number_string = str(number)

print(number_string)

Output:

123
# Join a list of strings into a single string, separated by a comma.
names = ["Alice", "Bob", "Carol"]

names_string = ",".join(names)

print(names_string)

Output:

Alice,Bob,Carol

You can also use string formatting to create new strings. String formatting is the process of inserting values into a string template. There are a number of different string formatting options available in Python, but the most common is to use the f-strings syntax.

Here is an example of using f-strings to create a new string:

name = "Alice"
age = 25

# Create a new string using f-strings.
greeting = f"Hello, {name}! You are {age} years old."

print(greeting)

Output:

Hello, Alice! You are 25 years old.

String formatting is a powerful tool that can be used to create complex strings with ease.

By following these tips, you will be able to create new strings in Python with ease.

Try using the index method yourself now!

Using the index method, find out the position of “x” in “supercalifragilisticexpialidocious”.

word = "supercalifragilisticexpialidocious"
print(word.index("x"))

Here is your output:
21

Right on! The index method is a very useful way of working
with strings, and not having to do the hard work manually.

[MUSIC] In the last video, we saw how to access
certain characters inside a string. Now, what if we wanted to change them? Imagine you have a string with a character
that’s wrong and you want to fix it, like this one. Taking into account what you learned about
string indexing, you might be tempted to fix it by accessing the corresponding
index and changing the character. Let’s see what happens if we try that. These pesky type errors, right? In this case, we’re told that strings
don’t support item assignment. This means that we can’t change individual
characters because strings in Python are immutable, which is just a fancy word
meaning they can’t be modified. What we can do is create a new string
based on the old one, like this. Nice, we fixed the typo. But does this mean the message
variable can never change? Not really. We can assign a new value
to the same variable. Let’s do that a couple of
times to see how it works. What we’re doing here, is giving
the message variable a whole new value. We’re not changing the underlying
string that was assigned to it before. We’re assigning a whole new
string with different content. If this seems a bit complex, that’s okay. You don’t need to worry
about this right now. We’ll call this out whenever it’s
relevant for the programmer writing. So, we figured out how to create
a new message from the old one. But how are we supposed to know
which character to change? Let’s try something different. In this case, we’re using a method to
get the index of a certain character. A method is a function associated
with a specific class. We’ll talk a lot more about classes and
methods later. For now, what you need to know is that
this is a function that applies to a variable. And we can call it by following
the variable with a dot. Let’s try this a few more times. So the index method returns the index of
the given substring, inside the string. The substring that we pass,
can be as long or as short as we want. What if there’s more than
one of the substring? Here, we know there are two s characters,
but we only get one value. That’s because the index method returns
just the first position that matches. And what happens if the string doesn’t
have the substring we’re looking for? The index method can’t return a number
because the substring isn’t there, so we get a value error instead. We said that if the substring
isn’t there, we would get an error. So how can we know if a substring is
contained in a string to avoid the error? Let’s check this out. We can use the key word in to check if
a substring is contained in a string. We came across the keyword in,
when using four loops. In that case, it was used for iteration. Here, it’s a conditional that
can be either true or false. It’ll be true if the substring is part
of the string, and false if it’s not. So here, the Dragons substring
isn’t part of the string, and sadly, we can’t have a Dragon as a pet. All right, we just covered a bunch of
new things and you’re doing awesome. Let’s put all the stuff together
to solve a real-world problem. Imagine that your company has recently
moved to using a new domain, but a lot of the company email addresses
are still using the old one. You want to write a program that replaces
this old domain with the new one in any outdated email addresses. The function to replace
the domain would look like this. This function is a bit more
complex than others, so let’s go through it line by line. First, we define the replace_domain
function which accepts three parameters. The email address to be checked,
the old domain, and the new domain. Having all these values as parameters
instead of directly in the code, makes our function reusable. We aren’t just changing
one domain to the other, we have a function that
will work with all domains. Pretty sweet. In the first line of
the body of the function, we check if the concatenation
of the @ sign and the old domain are contained in
the email address, using the keyword in. We check this to make sure the email
has “old domain” on the portion that comes after the @ sign. If the condition is true,
the email address needs to be updated. To do that, we first find out
the index where the old domain, including the @ sign starts. We know that this index will be a valid
number because we’ve already checked that the substring was present. So, using this index,
we create the new email. This is a string that contains
the first portion of the old email, up until the index we had calculated,
followed by the @ sign and the new domain. Finally, we return this new email. If the email didn’t
contain the new domain, then we can just return it,
which is what we do in the last line. Wow, that was a really complex function
with a lot of new things in it. So don’t worry if you’re
finding it a bit tricky. Re-watch the video and take your time. If there’s a specific part that’s
tripping you up, remember, you can always ask your fellow learners
for help in the discussion forum. You may even find that
someone has asked and got the answer to the same
question already. When you feel ready to move on,
meet me over in the next video, where we’re going to learn a lot
more handy string methods.

Reading: Basic String Methods

Reading

Video: More String Methods

Python provides a number of string methods that can be used to perform various operations on strings. Some of these methods include:

  • upper() and lower(): These methods convert the string to all upper or lower case, respectively.
  • strip(), lstrip(), and rstrip(): These methods remove whitespace characters from the beginning and/or end of the string.
  • count(): This method returns the number of times a given substring appears in the string.
  • endswith(): This method returns whether the string ends with a given substring.
  • isnumeric(): This method returns whether the string contains only numeric characters.
  • int(): This function converts a numeric string to an integer.
  • join(): This method concatenates a list of strings using a specified separator.
  • split(): This method splits a string into a list of strings using a specified separator.

These are just a few of the many string methods that are available in Python. You can find a complete list of string methods in the Python documentation.

Examples of using string methods:

# Convert the string to upper case.
my_string = "This is my string."
upper_case_string = my_string.upper()
print(upper_case_string)

# Remove whitespace characters from the beginning and end of the string.
my_string = "   This is my string.   "
stripped_string = my_string.strip()
print(stripped_string)

# Count the number of times a given substring appears in the string.
my_string = "This is my string."
count = my_string.count("is")
print(count)

# Check if the string ends with a given substring.
my_string = "This is my string."
endswith = my_string.endswith(".")
print(endswith)

# Check if the string contains only numeric characters.
my_string = "1234567890"
isnumeric = my_string.isnumeric()
print(isnumeric)

# Convert a numeric string to an integer.
my_string = "123"
integer = int(my_string)
print(integer)

# Concatenate a list of strings using a specified separator.
my_list = ["This", "is", "my", "string."]
joined_string = " ".join(my_list)
print(joined_string)

# Split a string into a list of strings using a specified separator.
my_string = "This is my string."
split_list = my_string.split(" ")
print(split_list)

Output:

THIS IS MY STRING.
This is my string.
2
True
True
123
This is my string.
['This', 'is', 'my', 'string.']

Conclusion:

String methods are a powerful tool that can be used to perform various operations on strings. By understanding how to use string methods, you can write more efficient and robust code.

More String Methods in Python

In addition to the string methods that we covered in the previous tutorial, there are many other useful string methods available in Python. Here is a summary of some of these more advanced string methods:

  • capitalize(): This method converts the first letter of the string to upper case and the rest of the string to lower case.
  • center(): This method centers the string within a specified width.
  • find() and rfind(): These methods return the index of the first or last occurrence of a substring in the string, respectively.
  • isalnum(), isalpha(), isdecimal(), and isspace(): These methods return True if the string contains only alphanumeric characters, alphabetic characters, decimal characters, or whitespace characters, respectively.
  • ljust() and rjust(): These methods left-justify and right-justify the string within a specified width, respectively.
  • partition() and rpartition(): These methods split the string into three parts at the first or last occurrence of a substring, respectively.
  • replace() and translate(): These methods replace all occurrences of a substring in the string with another substring. The translate() method can also be used to translate characters in the string to different characters.
  • splitlines() and joinlines(): These methods split and join the string into and from a list of lines, respectively.
  • zfill(): This method fills the string with zeros to the left until it reaches a specified width.

Examples:

# Capitalize the first letter of the string.
my_string = "this is my string"
capitalized_string = my_string.capitalize()
print(capitalized_string)

# Center the string within a specified width.
my_string = "this is my string"
centered_string = my_string.center(20)
print(centered_string)

# Find the index of the first occurrence of a substring in the string.
my_string = "this is my string"
index = my_string.find("is")
print(index)

# Check if the string contains only alphanumeric characters.
my_string = "this123"
isalnum = my_string.isalnum()
print(isalnum)

# Left-justify the string within a specified width.
my_string = "this is my string"
left_justified_string = my_string.ljust(20)
print(left_justified_string)

# Split the string at the first occurrence of a substring.
my_string = "this is my string"
split_list = my_string.partition(" ")
print(split_list)

# Replace all occurrences of a substring in the string with another substring.
my_string = "this is my string"
replaced_string = my_string.replace("is", "are")
print(replaced_string)

# Split the string into a list of lines.
my_string = "this is my\nmultiline string"
splitlines_list = my_string.splitlines()
print(splitlines_list)

# Join a list of lines into a string.
my_list = ["this is my", "multiline string"]
joinlines_string = "\n".join(my_list)
print(joinlines_string)

# Fill the string with zeros to the left until it reaches a specified width.
my_string = "123"
zero_filled_string = my_string.zfill(10)
print(zero_filled_string)

Output:

This is my string
       this is my string
2
True
this is my string    
('this', ' ', 'my string')
this are my string
['this is my', 'multiline string']
this is my
multiline string
0000000123

Conclusion:

The string methods in Python provide a powerful and flexible way to manipulate strings. By understanding how to use these methods, you can write more efficient and robust code.

We said earlier that we had a lot
of new exciting concepts coming up. Well, I’m not going to
string you along anymore. We’re going to tie up our lessons on
strings with a bunch of fun methods for transforming our string text. I know, I know,
my jokes are pretty terrible, so let’s get back to the good stuff. So far, we’ve seen ways you can access
portions of strings using the indexing technique, create new strings by slicing
and concatenating, find characters and strings using the index method, and
even test if one string contains another. On top of all this
string processing power, the string class provides a bunch of
other methods for working with text. Now, we’ll show you how to
use some of these methods. Remember, the goal is not for
you to memorize all of this. Instead, we want to give you an idea of
what you can do with strings in Python. Some string methods let you
perform transformations or formatting on the string text,
like upper, and its opposite, lower. These methods are really useful
when you’re handling user input. Let’s say you wanted to check if
the user answered yes to a question. How would you know if the user
typed it using upper or lower case? You don’t need to, you just transform
the answer to the case you want. Like this example. Another useful method when dealing
with user input is the strip method. This method will get rid of
surrounding spaces in the string. If we ask the user for an answer, we usually don’t care about
any surrounding spaces. So it’s a good idea to use the strip
method to get rid of any white space. This means that strip doesn’t just
remove spaces, it also removes tabs and new line characters, which are all characters we don’t
usually want in user-provided strings. There are two more versions of
this method, lstrip rstrip, to get rid of the whitespace
characters just to the left or to the right of the string
instead of both sides. Other methods give you information
about the string itself. The method count returns how many times
a given substring appears within a string. The method endswith returns whether
the string ends with a certain substring. The method isnumeric returns whether
the string’s made up of just numbers. Adding to that,
if we have a string that is numeric, we can use the int function to
convert it to an actual number. In earlier videos, we showed that we can
concatenate strings using the plus sign. The join method can also be used for
concatenating. To use the join method, we have to call it
on the string that’ll be used for joining. In this case,
we’re using a string with a space in it. The method receives a list of strings and returns one string with each of
the strings joined by the initial string. Let’s check out another example. Finally, we can also split
a string into a list of strings. The split method returns a list of all
the words in the initial string and it automatically splits by any whitespace. It can optionally take a parameter and split the strings by another character,
like a comma or a dot. Are you starting to see how these string
methods could be useful in your IT job? Okay, so
we’ve just learned a bunch of new methods. But there are tons more that
you can use on strings. We’ve included a list with
the ones we talked about, and some new ones in the next cheat sheet. You’ll also find a link to the full
Python documentation there, which gives you all the info
on each available method. As we’ve said before, don’t worry
about trying to memorize everything. You’ll pick these concepts
up with practice, and the documentation is always
there if you need it. All right,
last up in our string of string videos, we’re going to check out
how to format strings.

Reading: Advanced String Methods

Reading

Video: Formatting Strings

The format() method is a powerful way to format strings in Python. It allows you to insert values into strings and to format those values in a variety of ways.

Basic usage:

To use the format() method, you simply pass the string you want to format to the format() method, along with a tuple of values to be inserted into the string. The placeholders for the values are curly braces ({}).

For example, the following code will print the string “Hello, John!” to the console:

name = "John"
message = "Hello, {}!".format(name)
print(message)

Formatting expressions:

You can also use formatting expressions inside the curly braces to format the values. For example, the following code will print the price of an item with and without tax, formatted to two decimal places:

price = 7.5
tax_rate = 0.09
price_with_tax = price * (1 + tax_rate)

# Format the price to two decimal places.
price_with_tax_formatted = "{:.2f}".format(price_with_tax)

# Print the results.
print("Price without tax: ${:.2f}".format(price))
print("Price with tax: ${}".format(price_with_tax_formatted))

Output:

Price without tax: $7.50
Price with tax: $8.18

String formatting in the real world:

String formatting is a powerful tool that can be used to make your code more readable and informative. It can also be used to create error messages, logging messages, and other types of output.

For example, you could use string formatting to create a custom error message that includes the name of the variable that caused the error and the value of that variable. This would help you to debug your code more quickly and easily.

Conclusion:

The format() method is a powerful tool for formatting strings in Python. By understanding how to use the format() method, you can write more readable, informative, and robust code.

Formatting Strings in Python

Python provides a number of ways to format strings. The simplest way is to use the + operator to concatenate strings. For example:

name = "Alice"
greeting = "Hello, " + name + "!"
print(greeting)

Output:

Hello, Alice!

However, this method can become cumbersome if you need to format more complex strings. For example, if you need to format a string with multiple variables, you will need to use the str() function to convert each variable to a string before concatenating it.

A more powerful way to format strings is to use the format() method. The format() method allows you to insert values into strings and to format those values in a variety of ways.

To use the format() method, you simply pass the string you want to format to the format() method, along with a tuple of values to be inserted into the string. The placeholders for the values are curly braces ({}).

For example, the following code will print the string “Hello, John!” to the console:

name = "John"
message = "Hello, {}!".format(name)
print(message)

Output:

Hello, John!

You can also use formatting expressions inside the curly braces to format the values. For example, the following code will print the price of an item with and without tax, formatted to two decimal places:

price = 7.5
tax_rate = 0.09
price_with_tax = price * (1 + tax_rate)

# Format the price to two decimal places.
price_with_tax_formatted = "{:.2f}".format(price_with_tax)

# Print the results.
print("Price without tax: ${:.2f}".format(price))
print("Price with tax: ${}".format(price_with_tax_formatted))

Output:

Price without tax: $7.50
Price with tax: $8.18

Here is a summary of some of the most common formatting expressions:

ExpressionDescription
:.2fFormat a float number to two decimal places.
:.4eFormat a float number to four decimal places in scientific notation.
:.3%Format a float number as a percentage with three decimal places.
>10Right-align the value to ten spaces.
<10Left-align the value to ten spaces.
^10Center the value in ten spaces.

You can also use the format() method to format dates and times. For example, the following code will print the current date and time in a variety of formats:

import datetime

now = datetime.datetime.now()

# Print the current date and time in ISO 8601 format.
print(now.isoformat())

# Print the current date and time in a more human-readable format.
print(now.strftime("%A, %d %B %Y, %H:%M:%S"))

Output:

2023-09-28T21:42:00+00:00
Wednesday, 28 September 2023, 21:42:00

The format() method is a powerful tool for formatting strings in Python. By understanding how to use the format() method, you can write more readable, informative, and robust code.

Here are some additional tips for formatting strings in Python:

  • Use the format() method for all but the simplest string formatting tasks.
  • Use formatting expressions to format values in a variety of ways.
  • Use the format() method to format dates and times.
  • Use the str() function to convert variables to strings before concatenating them.
  • Use string formatting to make your code more readable, informative, and robust.

[MUSIC] Up to now we’ve been making strings
using the plus sign to just concatenate the parts of the string
we wanted to create. And we’ve used the str function to
convert numbers into strings so that we can concatenate them, too. This works, but it’s not ideal, especially when the operations you want to
do with the string or on the tricky side. There’s a better way to do
this using the format method. Let’s see a couple of examples. In this example, we have two variables,
name and number. We generate a string that has those
variables in it by using the curly brackets placeholder to show where
the variables should be written. We then pass the variables as
a parameter to the format method. See how it doesn’t matter that name
is a string and number is an integer? The format method deals with that,
so we don’t have to. Pretty neat, right? The curly brackets aren’t always empty. By using certain expressions
inside those brackets, we can take advantage of the full
power of the format expression. Heads up, this can get complex fast. If at any point, you get confused, don’t
panic, you only really need to understand the basic usage of the format
method we just saw. One of the things we can put inside
the curly brackets is the name of the variable we want in that position
to make the whole string more readable. This is particularly relevant when the
text can get rewritten or translated and the variables might switch places. In our earlier example, we could rewrite the message to make
the variables appear in a different order. In that case, we’d need to pass the parameters to
format in a slightly different way. Because we’re using placeholders with
variable names, the order in which the variables are passed to
the format function doesn’t matter. But for this to work, we need to set
the names we’re going to use and assign a value to them inside
the parameters to format. And that’s just the tip of the iceberg of
what we can do with the format method. Want to dive a little deeper? Great, let’s keep on going. We’re going to check out
a different example. Let’s say you want to output the price
of an item with and without tax. Depending on what the tax rate is, the number might be a long
number with a bunch of decimals. So if something costs $7.5 without tax and the tax rate is 9%,
the price with tax would be $8.175. First off, ouch, and also, since there’s
no such thing as half a penny anymore, that number doesn’t make sense. So to fix this we can make the format
function print only two decimals, like this. In this case between the curly brackets
we’re writing a formatting expression. There are a bunch of different
expressions we can write. These expressions are needed when we want
to tell Python to format our values in a way that’s different from the default. The expression starts with a colon to
separate it from the field name that we saw before. After the colon, we write .2f. This means we’re going to
format a float number and that there should be two
digits after the decimal dot. So no matter what the price is,
our function always prints two decimals. Remember when we did the table to convert
from Fahrenheit to Celsius temperatures? Our table looked kind of ugly because it
was full of float numbers that had way too many decimal digits. Using the format function,
we can make it look a lot nicer. In these two expressions we’re using
the greater than operator to align text to the right so
that the output is neatly aligned. In the first expression we’re saying
we want the numbers to be aligned to the right for a total of three spaces. In the second expression we’re saying we
want the number to always have exactly two decimal places and we want to align
it to the right at six spaces. We can use string formatting like this to
make the output of our program look nice and also to generate useful logging and
debugging messages. Over the course of my sysadmin career, I’ve grown used to formatting strings to
create more informative error messages. They help me understand what’s going
on with a script that’s failing. There’s a ton more formatting options
you can use when you need them. But don’t worry about
learning them all at once, we’ll explain any others as they come
along and we’ll put everything in a cheat sheet that you can refer to whenever
you need a formatting expression. Let’s take a look at that now and then we’ll have a quiz to help you get
more familiar with all this new knowledge.

Reading: String Formatting

Reading

Reading: String Reference Cheat Sheet

Reading

Reading: Formatting Strings Cheat Sheet

Reading

Practice Quiz: Strings

The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like “Never Odd or Even”. Fill in the blanks in this function to return True if the passed string is a palindrome, False if not.

Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase “X miles equals Y km”, with Y having only 1 decimal place. For example, convert_distance(12) should return “12 miles equals 19.2 km”.

If we have a string variable named Weather = “Rainfall”, which of the following will print the substring or all characters before the “f”?

Fill in the gaps in the nametag function so that it uses the format method to return first_name and the first initial of last_name followed by a period. For example, nametag(“Jane”, “Smith”) should return “Jane S.”

The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occurrence of the old string in the sentence, only the one at the end is replaced, not all of them. For example, replace_ending(“abcabc”, “abc”, “xyz”) should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending(“abcabc”, “ABC”, “xyz”) should return abcabc (no changes made).

Lists


Video: What is a list?

This video introduces the list data type in Python. Lists are collections of items that can be of different types. They are similar to strings in that they can be indexed and sliced. However, lists can contain any type of data, while strings can only contain characters.

The video also discusses some of the basic operations that can be performed on lists, such as checking if a list contains a certain element, accessing individual elements, and creating slices of the list.

The video concludes by noting that lists and strings are both examples of sequences in Python. This means that they share some common operations, such as iterating over them using for-loops and using the len function to get the length of the sequence.

Overall, this video provides a good introduction to the list data type in Python. It covers the basics of how lists work and how to perform some common operations on them.

What is a list in Python?

A list in Python is a collection of items that can be of any type. Lists are similar to arrays in other programming languages, but they are more flexible and powerful.

Lists are created using square brackets. For example, the following code creates a list of strings:

my_list = ["apple", "banana", "cherry"]

Lists can also contain other lists. For example, the following code creates a list of lists:

nested_list = [[1, 2, 3], ["a", "b", "c"]]

Lists can be accessed using indexes. The first item in a list has an index of 0, the second item has an index of 1, and so on. For example, the following code prints the first item in the my_list list:

print(my_list[0])

Output:

apple

Lists can also be sliced. Slicing allows you to extract a subset of a list. For example, the following code extracts the second and third items from the my_list list:

my_list_slice = my_list[1:3]

The my_list_slice variable will now contain the following list:

["banana", "cherry"]

Lists can be modified by adding, removing, and changing items. For example, the following code adds the string “orange” to the end of the my_list list:

my_list.append("orange")

The my_list variable will now contain the following list:

["apple", "banana", "cherry", "orange"]

Lists are a powerful data structure that can be used to store and manipulate collections of data. They are one of the most commonly used data structures in Python.

Here are some of the common operations that can be performed on lists in Python:

  • Accessing items: Items in a list can be accessed using indexes.
  • Slicing: Slices of a list can be extracted using the [start:end] syntax.
  • Adding items: Items can be added to the end of a list using the append() method.
  • Removing items: Items can be removed from a list using the remove() method.
  • Changing items: Items in a list can be changed by accessing them using their index.
  • Iterating over lists: Lists can be iterated over using for loops.

Lists are a versatile and powerful data structure that can be used to solve a variety of programming problems.

Using the “split” string method from the preceding lesson, complete the get_word function to return the {n}th word from a passed sentence. For example, get_word(“This is a lesson about lists”, 4) should return “lesson”, which is the 4th word in this sentence. Hint: remember that list indexes start at 0, not 1.

def get_word(sentence, n):
	# Only proceed if n is positive 
	if n > 0:
		words = sentence.split()
		# Only proceed if n is not more than the number of words 
		if n <= len(words):
			return words[n-1]
	return("")

print(get_word("This is a lesson about lists", 4)) # Should print: lesson
print(get_word("This is a lesson about lists", -4)) # Nothing
print(get_word("Now we are cooking!", 1)) # Should print: Now
print(get_word("Now we are cooking!", 5)) # Nothing
Here is your output: lesson Now Excellent! You're getting comfortable with string conversions into lists. Now we are really cooking!

As you know by now, Python comes with a lot of
ready-to-use data types. We’ve seen integers, floats, Booleans, and strings in detail. But those data types can
only take you so far. Eventually in your scripts, you want to develop code that manipulates collections of items like a list of
strings representing all the file names in a directory or a list of integers representing the size
of network packets. This is where the list
data type comes in handy. You can think of lists
as long boxes with the space inside the box divided
up into different slots. Each slot can contain
a different value. Like we mentioned earlier when we first came across the list, in Python, we use
square brackets to indicate where the
list starts and ends. Let’s check out an example. Here, we’ve created a
new variable called x and set its contents to
be a list of strings. We can check the type of x using the type function we
saw a little while ago. Nice. Python tells
us this is a list. In the same way, we’ve
done with other variables, we can show the contents of the whole list using
the print function. The length of the list is
how many elements it has. To get that value, we’ll use the same len function
we used for strings. That’s right. Our list
has four elements. When calling Len for the list, it doesn’t matter how long
each string is on its own. What matters is how many
elements the list has. To check if a list contains
a certain element, you can use the keyword “in”
like in these examples. Again, like when we
use this with strings, the result of this
check is a Boolean, which we can use as a condition
for branching or looping. We can also use
indexing to access individual elements depending on their position in the list. To do that, we use the square brackets and the
index we want to access, exactly like we did with strings. Remember that the first element
is given the index zero. This means the last
index of the list will be the length of
the list minus one. What happens if we try to access an element after the
end of the list? You might have seen this coming. We get an index error. We can’t go over the
end of the list. Remember that because list
indexes start at zero, accessing the item
at index four means we’re trying to access the
fifth element in the list. There are only four elements. So we’re out of
range if we try to access the index number four. Does this seem a bit confusing? If it does, this visualization
might help you out. As you can see, index
four doesn’t point at anything since there’s no
slot four in our list. As with strings, we can also use indexes to create a
slice of the list. For this, we use ranges of two numbers separated by a colon. Again, the second element
isn’t included in the slice. So the range goes to the
second index minus one. Here, we start at
index one and go up to one less than
three, which is two. We can also leave out one
of the range indexes empty. The first value
defaults to zero and the second value to the length
of the list. Makes sense? If all this sounds really familiar to what we
said about strings, then this course is
working as intended. That’s because
strings and lists are very similar data types. In Python, strings and lists are both examples of sequences. There are other sequences too, and they all share a bunch of operations like iterating
over them using for-loops, indexing using the len function to know the length
of the sequence, using plus to concatenate
two sequences and using in to verify if the
sequence contains an element. So this is great news. While understanding
indexing is hard, once you know it
for one data type, you’ve pretty much mastered
it for every data type. So you actually know way
more than you thought. Wow, now, we’re really cooking. Next up, we’re going to look at some more list operations. This time, actually
specific to lists.

Reading: Lists Defined

Reading

Video: Modifying the Contents of a List

Lists are mutable, which means they can be changed. This means we can add, remove, or modify elements in a list.

Here are some of the methods that let us modify the contents of a list:

  • append(): Adds a new element to the end of the list.
  • insert(): Adds an element at a specific index in the list.
  • remove(): Removes the first occurrence of an element from the list.
  • pop(): Removes and returns an element from the list at a specific index.
  • assignment: Changes an element at a specific index in the list.

Modifying the contents of lists is a common task in programming. For example, we could use a list to store the hosts on a network and add or remove hosts as they come online or offline. Or, we could use a list to store the users authorized to run a certain process and add or remove users when permissions are granted or removed.

Lists are a powerful tool for storing and manipulating data. By understanding how to modify the contents of lists, we can write more efficient and effective programs.

Tutorial on Modifying the Contents of a List in Python

Lists are a mutable data type in Python, which means that their contents can be changed. This makes lists very versatile and powerful tools for storing and manipulating data.

There are a number of ways to modify the contents of a list in Python. Here are some of the most common methods:

  • append(): Adds a new element to the end of the list.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)

Output:

['apple', 'banana', 'cherry', 'orange']
  • insert(): Adds an element at a specific index in the list.
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "mango")
print(fruits)

Output:

['apple', 'mango', 'banana', 'cherry']
  • remove(): Removes the first occurrence of an element from the list.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)

Output:

['apple', 'cherry']
  • pop(): Removes and returns an element from the list at a specific index.
fruits = ["apple", "banana", "cherry"]
fruit = fruits.pop(1)
print(fruits)
print(fruit)

Output:

['apple', 'cherry']
'banana'
  • assignment: Changes an element at a specific index in the list.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)

Output:

['apple', 'mango', 'cherry']

These are just a few of the ways to modify the contents of a list in Python. By understanding these methods, you can write more efficient and effective programs.

Here are some examples of how to use these methods to modify the contents of a list:

  • Add the names of your friends to a list.
  • Remove a friend from the list if they move away.
  • Insert a new friend into the list at a specific position.
  • Change the name of a friend in the list.
  • Sort the list of friends alphabetically.
  • Print the list of friends to the console.

These are just a few ideas for how to use lists to store and manipulate data. By understanding how to modify the contents of lists, you can write programs that can do a variety of tasks.

One of the ways that
lists and strings are different is that
lists are mutable. Which is another fancy word
to say that they can change. This means we can add, remove, or modify elements in a list. Let’s go back to our example of thinking of a list as a long box. Changing the list means we
keep the same box and we add, remove, or change the
elements inside that box. We’ll now go through
the methods that let us modify the
list one by one. If all these details seem a little overwhelming, that’s okay. As usual, there will be a cheat sheet at
the end and you’ll have lots of chances to practice each of these methods
as we go along. You don’t need to learn
all those by heart, and of course you can always review anything that isn’t clear. So don’t worry, we got your back. We’ll start with the
simplest change; adding an element to a list
using the append method. Let’s check this out in
the tastiest example yet. The append method adds a new element at the
end of the list. It doesn’t matter how
long the list is. The element always
gets added to the end. You could start with
an empty list and add all of its
items using append. If you want to insert an element
in a different position, instead of at the end, you can use the insert method. The insert method
takes an index as the first parameter and an element as the
second parameter. It adds the element at
that index in the list. To add it as the first element, we use index zero and we
can use any other number. What happens if we use a number larger than the
length of the list? No errors. You can say that
it even worked just peachy. If we use an index higher
than the current length, the element just gets
added to the end. You can pass any number
to insert but usually, you either add at the
beginning using insert at the zero index or at
the end using append. We can also remove
elements from the list. We can do it using the value of the element
we want to remove. Can you guess what
method we would use? You got it, use
the remove method. The remove method removes from the list the first occurrence of the element we pass to it. What happens if the element
is not in the list? That went pear-shaped. We got a value error, telling us the element
isn’t in the list. Another way we can remove elements is by using
the pop method, which receives an index. The pop method returns
the element that was removed at the index
that was passed. In the last way to modify the contents of a
list is to change an item by assigning something else to that position, like this. Wow, the contents of our fruits variable have changed a lot
since we started this video. But it’s always the same
variable, the same box. We’ve just modified
what’s inside. Modifying the contents
of lists will come up in tons of scripts as
we operate with them. If the list contains
hosts on a network, you could add or remove hosts as they come
online or offline. If the list contains users authorized to run
a certain process, you could add or
remove users when permissions are granted
or removed and so on. You’ve now seen a
number of methods that let us modify the
contents of a list, adding, removing, and changing the elements that are
stored inside the list. Whenever you need to
write a program that’ll handle a variable
amount of elements, you’ll use a list. What if you need a sequence of a fixed amount of elements? That’s coming up
in our next video.

Reading: Modifying Lists

Reading

Video: Lists and Tuples

Tuples are a sequence data type in Python that is immutable, meaning that their contents cannot be changed once they are created. Tuples are written in parentheses instead of square brackets.

Tuples are useful for representing data that has more than one value and that needs to be kept together. For example, you could use a tuple to store the name and email address of a person, or a date and time and the general health of the system at any point in time.

Tuples are also commonly used as the return value of functions that return more than one value.

Here are some of the benefits of using tuples:

  • Immutability: Tuples are immutable, which means that their contents cannot be changed once they are created. This can be useful for ensuring that data remains consistent.
  • Performance: Tuples are generally faster than lists, especially when accessing individual elements.
  • Readability: Tuples can make code more readable and easier to maintain.

Here are some of the drawbacks of using tuples:

  • Limited functionality: Tuples are less versatile than lists, as they cannot be modified.
  • Less efficient for certain tasks: Tuples can be less efficient than lists for certain tasks, such as inserting or removing elements from the middle of a sequence.

Overall, tuples are a useful data type in Python for representing data that has more than one value and that needs to be kept together. They are also commonly used as the return value of functions that return more than one value.

Tutorial on Lists and Tuples in Python

Lists and tuples are two of the most common data types in Python. They are both sequences of elements, but they have some key differences.

Lists

Lists are mutable, meaning that their contents can be changed after they are created. Lists are written in square brackets.

Here is an example of a list:

my_list = ["apple", "banana", "cherry"]

We can add elements to a list using the append() method:

my_list.append("orange")

We can remove elements from a list using the remove() method:

my_list.remove("banana")

We can access elements in a list using the [] operator:

first_element = my_list[0]

This will return the first element in the list, which is “apple”.

Tuples

Tuples are immutable, meaning that their contents cannot be changed after they are created. Tuples are written in parentheses.

Here is an example of a tuple:

my_tuple = ("apple", "banana", "cherry")

We cannot add, remove, or modify elements in a tuple.

We can access elements in a tuple using the [] operator, but we cannot change them.

first_element = my_tuple[0]

This will return the first element in the tuple, which is “apple”.

When to use lists and tuples

Lists are a good choice for data that needs to be mutable, such as a shopping cart or a list of tasks to do. Tuples are a good choice for data that needs to be immutable, such as a configuration file or a list of coordinates.

Here are some specific examples of when to use lists and tuples:

  • Lists:
    • To store a list of items that need to be purchased.
    • To store a list of tasks that need to be completed.
    • To store a list of students in a class.
  • Tuples:
    • To store a configuration file for a software application.
    • To store a list of coordinates for a map.
    • To store the results of a mathematical function.

Conclusion

Lists and tuples are both powerful data types in Python. Lists are mutable, while tuples are immutable. The best choice for a particular situation will depend on the specific needs of the application.

Let’s use tuples to store information about a file: its name, its type and its size in bytes. Fill in the gaps in this code to return the size in kilobytes (a kilobyte is 1024 bytes) up to 2 decimal places.

def file_size(file_info):
	name, file_type, file_size= file_info
	return("{:.2f}".format(file_size / 1024))

print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46
print(file_size(('Notes', 'txt', 496))) # Should print 0.48
print(file_size(('Program', 'py', 1239))) # Should print 1.21
Here is your output:
17.46
0.48
1.21

Well done! Aren't tuples handy to keep the information
nicely organized for when we need it?

As we called out before, there are a number of data types in Python that are all sequences. Strings are sequences of
characters and are immutable. Lists are sequences of elements of any type and are mutable. A third data type that’s
a sequence and also closely related to
lists is the tuple. Tuples are sequences of elements of any type that are immutable. We write tuples in parentheses instead of square brackets. You might be wondering, why do we even need
another sequence type? Weren’t lists great? Yes, lists are great. They can hold any number of
elements and we can add, remove and modify their
contents as much as we want, but there are cases when we want to make sure an element in a certain position
or index refers to one specific thing
and won’t change. In these situations,
lists won’t help us. Thanks for nothing lists. In our example, we have a tuple that represents
someone’s full name. The first element of the
tuple is the first-name. The second element is
the middle initial, and the third element
is the last-name. If we add another element
somewhere in there, what would that
element represent? It would just be confusing and our code wouldn’t know
what to do with it, and that’s why modifying
isn’t allowed. In other words, when using tuples the position of the elements inside the tuple have meaning. Tuples are used for lots of
different things in Python. One common example is the
return value of functions. When a function returns
more than one value, it’s actually returning a tuple. Remember the function to
convert seconds to hours, minutes, and seconds that
we saw a while back? Here just to remind you. This function returns
three values. In other words, it
returns a tuple of three elements.
Let’s give it a try. We see the result is a tuple. What if we print it? We see that it has the three elements
we expect it to have. Remember, since this is a
tuple, the order matters. The first element
represents the hours, the second one
represents the minutes, and the third
represents the seconds. One interesting thing we can do with tuples is unpack them. This means that we
can turn a tuple of three elements into three
separate variables. Because the order won’t change, we know what those variables
are present, like this. So now we’ve split the tuple
into three separate values. We’ve seen before that we can
also do this directly when calling the function without the intermediate result variable. In Python, it’s really common to use tuples
to represent data that has more than one value and that needs to
be kept together. For example, you
could use a tuple to have a filename and it’s size, or you could store the name and email address of a person, or a date and time
and the general health of the system
at any point in time. Can you see how these different
data types could help you automate some of your IT
work? Pretty cool, right? Knowing when to use
tuples and when to use lists can seem a
little fuzzy at first, but don’t worry,
it’ll get clearer as we tackle more examples.

Reading: Tuples

Reading

Video: Iterating over Lists and Tuples

This video discusses how to iterate over lists in Python. It starts by showing how to iterate over a list of strings and calculate the total number of characters and the average length of the strings. It then shows how to use the enumerate function to iterate over a list of strings and print the index and the string at each index.

Next, the video shows how to use a for loop to iterate over a list of tuples containing two strings each. The first string is an email address and the second string is the full name of the person with that email address. The video then shows how to write a function that creates a new list containing one string per person including their name and the email address between angled brackets.

The video concludes by discussing some common errors when dealing with lists in Python. It warns against using the range function to iterate over the indexes of a list and then to access the elements through indexing. It also warns against modifying a list while iterating over it.

Overall, this video provides a good overview of how to iterate over lists in Python. It also discusses some common errors to avoid.

Iterating over Lists and Tuples in Python

Lists and tuples are two of the most common data structures in Python. They are both sequences of elements, but they have some key differences. Lists are mutable, meaning that their elements can be changed, while tuples are immutable, meaning that their elements cannot be changed.

One of the most common operations that we perform on lists and tuples is iteration. Iteration means going through each element in a sequence and performing some operation on each element.

To iterate over a list or tuple in Python, we use a for loop. The syntax for a for loop is as follows:

for element in sequence:
    # Do something with element

Where sequence is the list or tuple that we want to iterate over.

For example, the following code iterates over a list of strings and prints each string to the console:

strings = ["hello", "world", "python"]

for string in strings:
    print(string)
hello
world
python

We can also use the enumerate function to iterate over a list or tuple and get the index of each element. The enumerate function returns a tuple for each element in the sequence, where the first value in the tuple is the index of the element and the second value in the tuple is the element itself.

For example, the following code iterates over a list of strings and prints the index and the string at each index to the console:

strings = ["hello", "world", "python"]

for index, string in enumerate(strings):
    print(index, string)

Output:

0 hello
1 world
2 python

We can use iteration to perform a variety of operations on lists and tuples. For example, we can use iteration to:

  • Calculate the sum or average of the elements in a list
  • Find the maximum or minimum element in a list
  • Remove all of the elements from a list that meet a certain condition
  • Sort a list in ascending or descending order

Iteration is a powerful tool that allows us to process lists and tuples efficiently.

Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements function to return every other element from the list, this time using the enumerate function to check if an element is in an even position or an odd position.

def skip_elements(elements):
	list = []
	for index, element in enumerate(elements):
		if index % 2 == 0:
			list.insert(index, element)
	return list

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
Here is your output:
['a', 'c', 'e', 'g']
['Orange', 'Strawberry', 'Peach']

Great job! The enumerate function sure makes things easier,
doesn't it?

When we looked at for loops, we said they iterate over
a sequence of elements. One of the examples we checked out was iterating over a list. Let’s take a little trip to the zoo to see this in action. So we will make a
list of animals, so animals equals, and
since we’re making a list, we’ll start with a bracket, and we’ll add lion, zebra, dolphin, and monkey and end the list with
another bracket. Chars equals 0, and we’ll start a loop:
for animal in animals, two spaces, chars plus
equals length of animals. Print total characters
average length.format chars, chars length animals. In this code, we’re iterating
over a list of strings. For each of the strings,
we get its length and add it to the total
amount of characters. At the end we print the
total and the average which we get by dividing the total by the
length of the list. You can see we’re using
the len function twice, once to get the length
of the string and then again to get the amount
of elements in the list. What if you wanted
to know the index of an element while going
through the list? You could use the range
function and then use indexing to access the elements at the
index that range returned. You could use a
range function and then use indexing to
access the elements at the index that
range just returned or you could just use
the enumerate function. Winners equals, we’ll make
a list, Ashley, Dylan, and Reese and close
the list for index, person in enumerate winners print curly brackets dash curly brackets.format index
plus one person. The enumerate function returns a tuple for each
element in the list. The first value in the tuple is the index of the element
in the sequence. The second value in the tuple is the element in the sequence. You’re the real winner with
the enumerate function. It does all the work for you. Pretty useful, right? Let’s use all of this now to solve a slightly more
interesting problem. Say you have a list of tuples containing two strings each. The first string is an
email address and the second is the full name of the person with
that email address. You want to write a
function that creates a new list containing
one string per person including their name and the email address
between angled brackets. the format usually used
in emails like this. So what do we need to do? We’ll start by
defining a function that receives a list of people, def full_emails, takes
the argument people. Remember, people is a
list of tuples where the first element is the email address and the
second one is the full name. So in our function, we’ll first create the
variable that we’ll use as a return value which will be a list and we’ll call it result. Result equals empty list. We’ll then iterate over
the list of people. We know this list contains
tuples of two strings each. So we’ll unpack the values directly when iterating
in variables that we’ll call email and name for
email and name in people. Now, our result variable is a list and it should
contain strings. So we’ll append to the
resulting string to the results list, result.append. The string that
will append will be formatted in the way we want. To do that, we’ll use the format method with the two variables
of our iteration. So curly brackets, curly brackets.format, name, and email. Once we’re done
with the iteration, we’ll return the list
which should now contain all the necessary
emails, return result. Will this work? What do you
think? Let’s try it out. Print full emails
Alex@example.com, Alex Diego. Shay@example.com is
the email and we’ll call Shay Brandt as the name. Yes, this worked as expected. Before we move on, a quick
word of caution about some common errors when
dealing with lists in Python. Because we use the range
function so much with for loops, you might be tempted to
use it for iterating over indexes of a list and then to access the elements
through indexing. You could be particularly
inclined to do this if you’re used to other
programming languages before. Because in some languages, the only way to access an element of a list is by using indexes. Real talk, this works
but looks ugly. It’s more idiomatic in Python to iterate through the
elements of the list directly or using enumerate when you need the indexes
like we’ve done so far. There are some
specific cases that do require us to iterate
over the indexes, for example, when we’re trying to modify the elements of
the list we’re iterating. By the way, if you’re
iterating through a list and you want to
modify it at the same time, you need to be very careful. If you remove elements from
the list while iterating, you’re likely to end up
with an unexpected result. In this case, it might be better to use a copy of
the list instead. We’ve now seen a bunch of different things we
can do with lists, and hopefully you’re starting
to see how they can be a very powerful tool in
your IT specialist toolkit. Next up, we’re going to learn a powerful technique
for creating lists.

Reading: Iterating Over Lists Using Enumerate

Reading

Video: List Comprehensions

List comprehensions are a concise way to create lists in Python. They work by iterating over a sequence and creating a new list based on the results of the iteration.

For example, the following code creates a list of multiples of 7 from 7 to 70:

multiples = [x * 7 for x in range(1, 11)]

This code can be rewritten using list comprehension as follows:

multiples = [x for x in range(1, 11) if x % 7 == 0]

List comprehensions can also be used to create lists based on the contents of other lists, tuples, strings, or any other Python sequence.

For example, the following code creates a list of the lengths of the strings in a list:

Python

languages = ["Python", "JavaScript", "Java", "C++"]
lengths = [len(language) for language in languages]

List comprehensions can also be used to filter lists based on a condition. For example, the following code creates a list of all the numbers between 0 and 100 that are divisible by 3:

z = [x for x in range(0, 101) if x % 3 == 0]

Whether or not to use list comprehensions is a matter of personal preference. They can make code more concise and readable, but they can also make it more difficult to understand, especially if they are used to pack too much information together.

In general, it is a good idea to be familiar with list comprehensions, especially if you are trying to understand someone else’s code.

List comprehensions are a concise way to create lists in Python. They work by iterating over a sequence and creating a new list based on the results of the iteration.

The syntax for a list comprehension is as follows:

[expression for item in sequence if condition]

where:

  • expression is the expression that will be evaluated for each item in the sequence
  • item is the current item in the sequence
  • sequence is the sequence that will be iterated over
  • condition is an optional condition that must be met for the item to be included in the new list

For example, the following code creates a list of multiples of 7 from 7 to 70:

multiples = [x * 7 for x in range(1, 11)]

This code can be rewritten using list comprehension as follows:

multiples = [x for x in range(1, 11) if x % 7 == 0]

List comprehensions can also be used to create lists based on the contents of other lists, tuples, strings, or any other Python sequence.

For example, the following code creates a list of the lengths of the strings in a list:

languages = ["Python", "JavaScript", "Java", "C++"]
lengths = [len(language) for language in languages]

List comprehensions can also be used to filter lists based on a condition. For example, the following code creates a list of all the numbers between 0 and 100 that are divisible by 3:

z = [x for x in range(0, 101) if x % 3 == 0]

Here are some more examples of list comprehensions:

# Create a list of squares of numbers from 1 to 10
squares = [x ** 2 for x in range(1, 11)]

# Create a list of even numbers from 1 to 100
even_numbers = [x for x in range(1, 101) if x % 2 == 0]

# Create a list of all the unique letters in a string
letters = ["a", "b", "c", "a", "b", "c"]
unique_letters = [letter for letter in letters if letter not in unique_letters]

# Create a list of all the positive numbers in a list of numbers
numbers = [-1, 0, 1, 2, 3]
positive_numbers = [x for x in numbers if x > 0]

List comprehensions can be a very powerful tool for creating lists in Python. They can make your code more concise and readable, and they can be used to perform complex operations on lists with very little code.

The odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1.

def odd_numbers(n):
    return [x for x in range(0, n+1) if x%2 != 0]

print(odd_numbers(5))  # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1))  # Should print [1]
print(odd_numbers(-1)) # Should print []
Here is your output:
[1, 3, 5]
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9, 11]
[1]
[]

Excellent! You're using the power of list comprehension to
do a lot of work in just one line!

[MUSIC] We’re almost done with our
deep dive into Python list. But before we continue to
our next data structure, let’s talk about creating
lists in a shorter way. Say we wanted to create a list
with multiples of 7 from 7 to 70, we could do it like this. So we create a list called multiples. Then for x in range(1,11). Multiples.append(x*7). Print multiples. This works fine and
is a good way of solving it. But because creating lists based on
sequences is such a common task Python provides a technique
called list comprehension, that lets us do it in just one line. This is how we would do the same
with list comprehension. Multiples =, we’ll start the list, [ x * 7 for x in range(1,11)], and close the list. Print(multiples), it should be the same. List comprehensions let us create new
lists based on sequences or ranges. So we can use this technique whenever we
want to create a list based on a range like in this example. Or based on the contents of a list a tuple
a string or any other Python sequence. The syntax tries to copy how you would
express these concepts with natural language, although it can
still be confusing sometimes. Let’s check out a different example. Say we have a list of strings with
the names of programming languages like this one, and we want to generate
a list of the length of the strings. We could iterate over the list and
add them using a pen like we did before. Or we could use a list comprehension like this lengths = [len(language) for language in languages], print(lengths). List comprehensions also let
us use a conditional clause. Say we wanted all the numbers that are divisible by 3 between 0 and a 100, we could create a list like this z = [x for x in range(0,101 ) if x module 3 == 0] print(z). In this case we just want the element
x to be a part of the list, but we only want the numbers where
the remainder of the division by 3 is 0. So we add the conditional
clause after the range. Using list comprehensions when programming
in Python is totally optional. Sometimes it can make the code look nicer
and more readable, at other times it can have the opposite effect, especially if we
try to pack too much information together. In general, it’s a good idea to know
that list comprehensions exist, especially when you’re trying to
understand someone else’s code. All right, we’ve now seen
a bunch of different methods we can use to operate with lists and
tuples, and Python provides even more of them
that we didn’t get to talk about. In our next reading you’ll find a list
of the most common operations and links to the official documentation
in case you want to learn more. After the reading you can practice
your new skills in the next quiz.

Reading: List Comprehensions

Reading

Reading: Lists and Tuples Operations Cheat Sheet

Reading

Practice Quiz: Lists

Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.

Let’s create a function that turns text into pig latin: a simple text transformation that modifies each word moving the first character to the end and appending “ay” to the end. For example, python ends up as ythonpay.

The permissions of a file in a Linux system are split into three sets of three permissions: read, write, and execute for the owner, group, and others. Each of the three values can be expressed as an octal number summing each permission, with 4 corresponding to read, 2 to write, and 1 to execute. Or it can be written with a string using the letters r, w, and x or – when the permission is not granted. For example: 640 is read/write for the owner, read for the group, and no permissions for the others; converted to a string, it would be: “rw-r—–” 755 is read/write/execute for the owner, and read/execute for group and others; converted to a string, it would be: “rwxr-xr-x” Fill in the blanks to make the code convert a permission in octal format into a string format.

Tuples and lists are very similar types of sequences. What is the main thing that makes a tuple different from a list?

The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, … For example, group_list(“g”, [“a”,”b”,”c”]) returns “g: a, b, c”. Fill in the gaps in this function to do that.

The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the sentence “Guest is X years old and works as __.” for each one. For example, guest_list((‘Ken’, 30, “Chef”), (“Pat”, 35, ‘Lawyer’), (‘Amanda’, 25, “Engineer”)) should print out: Ken is 30 years old and works as Chef. Pat is 35 years old and works as Lawyer. Amanda is 25 years old and works as Engineer. Fill in the gaps in this function to do that.

Dictionaries


Video: What is a dictionary?

Dictionaries are a data type in Python that are used to store key-value pairs. Keys are unique and can be of any data type, while values can be of any data type. Dictionaries are mutable, meaning that they can be changed after they are created.

To create a dictionary, you can use curly braces ({}) and separate each key-value pair with a comma. To access a value in a dictionary, you can use the key enclosed in square brackets ([]). You can also use the in keyword to check if a key exists in a dictionary.

To add an entry to a dictionary, you can use the square brackets ([]). If the key already exists, the value will be replaced. To delete an entry from a dictionary, you can use the del keyword.

Dictionaries are a very useful data type that can be used to store all sorts of information. For example, you could use a dictionary to store the names and ages of your friends, or the filenames and file extensions of all the files in a directory.

What is a dictionary in Python?

A dictionary in Python is a collection of key-value pairs. Keys are unique and can be of any data type, while values can be of any data type. Dictionaries are mutable, meaning that they can be changed after they are created.

Creating a dictionary

To create a dictionary, you can use curly braces ({}) and separate each key-value pair with a comma. For example:

my_dictionary = {
    "name": "Bard",
    "age": 1,
    "occupation": "Language model"
}

Accessing values in a dictionary

To access a value in a dictionary, you can use the key enclosed in square brackets ([]). For example, to get Bard’s name, you would use the following code:

name = my_dictionary["name"]

Checking if a key exists in a dictionary

You can use the in keyword to check if a key exists in a dictionary. For example, to check if the key “age” exists in my_dictionary, you would use the following code:

if "age" in my_dictionary:
    print("The key 'age' exists in the dictionary.")

Adding an entry to a dictionary

To add an entry to a dictionary, you can use the square brackets ([]). If the key already exists, the value will be replaced. For example, to add a new key-value pair to my_dictionary, you would use the following code:

my_dictionary["favorite_color"] = "blue"

Deleting an entry from a dictionary

To delete an entry from a dictionary, you can use the del keyword. For example, to delete the key “age” from my_dictionary, you would use the following code:

del my_dictionary["age"]

Using dictionaries

Dictionaries can be used to store all sorts of information. For example, you could use a dictionary to store the names and ages of your friends, or the filenames and file extensions of all the files in a directory.

Here is an example of how to use a dictionary to store the names and ages of your friends:

friends = {
    "Alice": 25,
    "Bob": 27,
    "Carol": 29
}

# Get Alice's age
alice_age = friends["Alice"]

# Print Alice's age
print(alice_age)

Output:

25

Dictionaries are a very powerful data type that can be used in all sorts of ways. If you are new to Python, I encourage you to learn more about dictionaries and how to use them.

[MUSIC] How are you feeling so far? Lists and strings are pretty cool, right? These tools let us do a ton
of neat stuff in our code so they can be super fun to experiment with. We’re now going to learn about
another data type, dictionaries. Like lists, dictionaries are used to
organize elements into collections. Unlike lists, you don’t access elements
inside dictionaries using their position. Instead, the data inside dictionaries take
the form of pairs of keys and values. To get a dictionary value we
use its corresponding key. Another way these two vary is while
in a list the index must be a number, in a dictionary you can use a bunch
of different data types as keys, like strings, integers,
floats, tuples, and more. The name dictionaries comes from how they
work in a similar way to human language dictionaries. In an English language dictionary
the word comes with a definition. In the language of a Python dictionary,
the word would be the key and the definition would be the value. Make sense? Let’s check out an example. You can create an empty dictionary in
a similar way to creating an empty list, except instead of square brackets
dictionaries use curly brackets to define their content. Once again,
we can use the type function to check that the variable we’ve just created is a dictionary x = {} type(x). Creating initialized dictionaries
isn’t too different from the syntax we used in earlier videos to create
initialized lists or tuples. But instead of a series of
slots with values in them, we have a series of keys
that point at values. Okay, let’s check out
an example dictionary. We’ll call it file_counts = and then {“jpeg”:10, “txt”:14, “csv”:2, “py”:}23 print(file_counts). In this file_counts dictionary,
we’ve stored keys that are strings, like jpg,
that point at integer values, like 10. When creating the dictionary we use colons
and between the key and the value and separate each pair by commas. In a dictionary, it’s perfectly fine to
mix and match the data types of keys and values like this and can be very useful. In this example, we’re using a dictionary
to store the number of files corresponding to each extension. It makes sense to encode the file
extension formatting in a string, while it’s natural to represent
a count as an integer number. Let’s say you want to find out how many
text files there are in the dictionary. To do this, you would use the key
txt to access its associated value. The syntax to do this may look familiar,
since we used something similar in our examples of indexing strings,
lists, and tuples. File_counts [“txt”]. You can also use the in keyword to check
if a key is contained in a dictionary. Let’s try a couple of keys. “jpg” in file_counts, True. “html” in file_counts, False. Dictionaries are mutable. You might remember what mutable
means from an earlier video. That’s right, it means we can
add remove and replace entries. To add an entry in a dictionary, just use
the square brackets to create the key and assign a new value to it. Let’s add a file count of eight for
a new CFG file extension and dictionary. file_counts [“cfg”] = 8 and then print(file_counts). This brings up an interesting
point about dictionaries. What do you think will happen if
we try to add a key that already exists in the dictionary? file_counts[“csv”] = 17, print(file_counts). When you use a key that
already exists to set a value, the value that was already paired
with that key is replaced. As you can see in this example, the value associated with the csv
key used to be 2, but it’s now 17. The keys inside of
a dictionary are unique. If we try to store two different
values for the same key, we’ll just replace one with the other. Last off, we can delete elements from a
dictionary with the del keyword by passing the dictionary and the key to the element
as if we were trying to access it. del file_counts[“cfg”] and print(file_counts). What do you think? Dictionaries seem pretty useful, right? We’ve now seen how to create
a dictionary and how to add, modify, and delete elements stored in the dictionary. Up next, we’ll discover some
interesting things we can do with them.

Reading: Dictionaries Defined

Reading

Video: Iterating over the Contents of a Dictionary

Dictionaries are a powerful data type that can be used to store all sorts of information. They are especially useful for counting elements and analyzing frequency.

To use a dictionary in a for loop, the iteration variable will go through the keys in the dictionary. If you want to access the associated values, you can either use the keys as indexes of the dictionary or you can use the items() method which returns a tuple for each element in the dictionary. The tuple’s first element is the key. Its second element is the value.

You can also use the keys() and values() methods to get just the keys or values of a dictionary.

Dictionaries are a great tool for counting elements and analyzing frequency because each key can be present only once. For example, you could use a dictionary to count the number of times each letter appears in a piece of text.

Here is an example of how to count the number of times each letter appears in a piece of text using a dictionary:

def count_letters(text):
  """Counts the number of times each letter appears in a piece of text.

  Args:
    text: A string.

  Returns:
    A dictionary mapping letters to their counts.
  """

  letter_counts = {}
  for letter in text:
    if letter not in letter_counts:
      letter_counts[letter] = 0
    letter_counts[letter] += 1
  return letter_counts


# Example usage:

text = "tenant"
letter_counts = count_letters(text)

print(letter_counts)

Output:

{'t': 1, 'e': 1, 'n': 2, 'a': 1}

Dictionaries can be a very useful tool when writing scripts. For example, you could use a dictionary to count how many times each type of error appears in a log file.

To iterate over the contents of a dictionary in Python, you can use a for loop. The iteration variable will go through the keys in the dictionary. If you want to access the associated values, you can either use the keys as indexes of the dictionary or you can use the items() method which returns a tuple for each element in the dictionary. The tuple’s first element is the key. Its second element is the value.

Here is an example of how to iterate over the contents of a dictionary using a for loop:

my_dictionary = {
    "name": "Bard",
    "age": 1,
    "occupation": "Language model"
}

# Iterate over the keys in the dictionary
for key in my_dictionary:
    print(key)

# Iterate over the keys and values in the dictionary
for key, value in my_dictionary.items():
    print(key, value)

Output:

name
age
occupation
name Bard
age 1
occupation Language model

You can also use the keys() and values() methods to get just the keys or values of a dictionary. Here is an example:

my_dictionary = {
    "name": "Bard",
    "age": 1,
    "occupation": "Language model"
}

# Get the keys of the dictionary
keys = my_dictionary.keys()
print(keys)

# Get the values of the dictionary
values = my_dictionary.values()
print(values)

Output:

{'name', 'age', 'occupation'}
['Bard', 1, 'Language model']

Iterating over the contents of a dictionary is a very common operation in Python. It can be used for a variety of tasks, such as printing the contents of a dictionary, counting the number of elements in a dictionary, or finding the value associated with a particular key.

Now, it’s your turn! Have a go at iterating over a dictionary!

Complete the code to iterate through the keys and values of the cool_beasts dictionary. Remember that the items method returns a tuple of key, value for each element in the dictionary.

cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"}
for x,y in cool_beasts.items():
    print("{} have {}".format(x,y))
Here is your output:
octopuses have tentacles
dolphins have fins
rhinos have horns

Nice job! Your dictionary skills are getting stronger and
stronger!

[MUSIC] It probably won’t come as a surprise that,
just like with strings lists and tuples, you can use for loops to iterate
through the contents of a dictionary. Let’s see how this looks in action. So file_counts = {“jpg”:10, “txt”:14, “csv”:2, “py”:23 and then }. And then for extension in file_counts: two spaces print extension. So if you use a dictionary in a for loop, the iteration variable will go
through the keys in the dictionary. If you want to access the associated
values, you can either use the keys as indexes of the dictionary or you can use
the items method which returns a tuple for each element in the dictionary. The tuple’s first element is the key. Its second element is the value. Let’s try that with our
example dictionary. For ext amount in file_counts.items(): print(“there are and then {} files with the .{} extension”.format(amount, ext)). Sometimes you might just be interested
in the keys of a dictionary. Other times you might
just want the values. You can access both with their
corresponding dictionary methods like this. file_counts.keys() file counts.values(). These methods return special data
types related to the dictionary, but you don’t need to worry
about what they are exactly. You just need to iterate them
as you would with any sequence. For value in file_counts.values(): print value. So we can use items to
get key value pairs, keys to get the keys, and
values to get just the values. Not too hard, right? Because we know that each key
can be present only once, dictionaries are a great tool for
counting elements and analyzing frequency. Let’s check out a simple example of
counting how many times each letter appears in a piece of text. In this code, we’re first
initializing an empty dictionary, then going through each
letter in the given string. For each letter, we check if it’s
not already in the dictionary. And in that case, we initialize an entry
in the dictionary with a value of zero. Finally, we increment the count for
that letter in the dictionary. To sum up, we’ve created a dictionary
where the keys are each of the letters present in the string and the values
are how many times each letter is present. Let’s try out a few example strings. Count_letters. Let’s say a, count_letters(“tenant”) Count_letters, and this time we’ll say a long string with a lot of letters. Here you can see how the dictionary can
have any number of entries and the pairs of key values always count how many of
each letter there are in the string. Also, do you see how our simple code
doesn’t distinguish between actual letters and special characters like a space? To only count the letters, we’d need to specify which characters
we’re taking into account. This technique might seem simple at first,
but it can be really useful in a lot of cases. Let’s say for example that you’re
analyzing logs in your server and you want to count how many times each
type of error appears in the log file. You could easily do this with a dictionary
by using the type of error as the key and then incrementing the associated value
each time you come across that error type. Are you starting to see how dictionaries
can be a really useful tool when writing scripts? Coming up, we’re going to learn how
to tell when to use dictionaries and when to use lists.

Reading: Iterating Over Dictionaries

Reading

Video: Dictionaries vs. Lists

Dictionaries vs. Lists in Python

Lists and dictionaries are two of the most commonly used data structures in Python. Both lists and dictionaries can be used to store data, but they have different strengths and weaknesses.

Lists are ordered collections of data. They can be used to store any type of data, including strings, numbers, and other lists. Lists are accessed using their index, which is an integer value starting at 0.

Dictionaries are unordered collections of data. They store data in key-value pairs. The keys can be any type of data, but the values must be the same type of data. Dictionaries are accessed using their keys.

Here is a table that summarizes the key differences between lists and dictionaries:

FeatureListDictionary
OrderedYesNo
KeysInteger indexesAny type of data
ValuesAny type of dataSame type of data
AccessUsing indexesUsing keys

When to use lists

Lists are a good choice for storing data that needs to be accessed in a specific order, such as a list of items in a shopping cart or a list of students in a class. Lists are also a good choice for storing data that needs to be updated frequently, such as a list of scores in a game or a list of tasks to be completed.

When to use dictionaries

Dictionaries are a good choice for storing data that needs to be accessed quickly and easily, such as a list of contact information or a list of product prices. Dictionaries are also a good choice for storing data that needs to be grouped together, such as a list of students grouped by class or a list of products grouped by category.

Examples

Here are some examples of how to use lists and dictionaries in Python:

# List example
my_list = ["apple", "banana", "orange"]

# Print the first item in the list
print(my_list[0])

# Print the last item in the list
print(my_list[-1])

# Add an item to the end of the list
my_list.append("grape")

# Remove an item from the list
my_list.remove("banana")

# Dictionary example
my_dictionary = {"apple": 1.5, "banana": 0.75, "orange": 1.0}

# Print the price of an apple
print(my_dictionary["apple"])

# Add a new item to the dictionary
my_dictionary["grape"] = 1.25

# Remove an item from the dictionary
del my_dictionary["orange"]

Conclusion

Lists and dictionaries are two of the most powerful data structures in Python. They can be used to store and manipulate data in a variety of ways. Choosing the right data structure for your needs will depend on the specific requirements of your program.

Reading: Dictionary Methods Cheat Sheet

Reading

Practice Quiz: Dictionaries

The email_list function receives a dictionary, which contains domain names as keys, and a list of users as values. Fill in the blanks to generate a list that contains complete email addresses (e.g. diana.prince@gmail.com).

The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. Fill in the blanks to return a dictionary with the users as keys and a list of their groups as values.

The dict.update method updates one dictionary with the items coming from the other dictionary, so that existing entries are replaced and new entries are added. What is the content of the dictionary “wardrobe“ at the end of the following code?

What’s a major advantage of using dictionaries over lists?

The add_prices function returns the total price of all of the groceries in the dictionary. Fill in the blanks to complete this function.

Module Review


Video: Basic Structures Wrap Up

This module covers basic Python data structures, including strings, lists, dictionaries, tuples, and sets. Knowing how to use these structures allows you to solve interesting problems with your programs.

If you’re feeling overwhelmed, don’t worry. It’s normal to feel that way when learning new concepts. Just keep practicing, and you’ll eventually get the hang of it.

Remember, you have the grit to learn how to script. Stick with it, and it will only get easier.

Conclusion:

Once you’re comfortable with the material, take the graded assessment to test your knowledge.

In this module, we’ve covered the basic structures
we can use to make the most of
our Python scripts; strings, lists, and dictionaries. We’ve also called out a couple of associated data types
like tuples and sets. Knowing your way around
these structures lets you solve interesting
problems with your programs. As we keep saying, the
key to mastering them and knowing when to use one
or the other is practice. The more you write scripts
that use these concepts, the easier it will become to pick the right one when you need it. So how are you feeling? We just learned a lot
of new concepts and it’s totally normal to
feel a little overwhelmed. If you’re feeling confident
that’s awesome and if you’re starting to think this is too hard for me
I’ll never get it, that’s also completely normal. We all felt like that at some point when
learning how to code. First off, you will get this. Second, if you’re
feeling a little iffy on any of the content
we’ve covered so far, now is the time to
re-watch the videos. Believe me, you’ll be amazed by how much you’ve
learned so far and a second review is
usually all you need to understand what might seem
a little tricky right now. Jobs in IT require
problem-solving and perseverance. You wouldn’t be here
right now if you didn’t have the grit to
learn how to script. So stick with it. I promised you that it’ll
only get easier and easier. To wrap up, we’ve got a graded assessment
to help you put all your new knowledge
to the test. Take it once you feel ready to. Take your time and
remember, you’ve got this.

Quiz: Module 4 Graded Assessment

The format_address function separates out parts of the address string into new strings: house_number and street_name, and returns: “house number X on street named Y”. The format of the input string is: numeric house number, followed by the street name which may contain numbers, but never by themselves, and could be several words long. For example, “123 Main Street”, “1001 1st Ave”, or “55 North Center Drive”. Fill in the gaps to complete this function.

The highlight_word function changes the given word in a sentence to its upper-case version. For example, highlight_word(“Have a nice day”, “nice”) returns “Have a NICE day”. Can you write this function in just one line?

A professor with two assistants, Jamie and Drew, wants an attendance list of the students, in the order that they arrived in the classroom. Drew was the first one to note which students arrived, and then Jamie took over. After the class, they each entered their lists into the computer and emailed them to the professor, who needs to combine them into one, in the order of each student’s arrival. Jamie emailed a follow-up, saying that her list is in reverse order. Complete the steps to combine them into one list as follows: the contents of Drew’s list, followed by Jamie’s list in reverse order, to get an accurate list of the students as they arrived.

Use a list comprehension to create a list of squared numbers (n*n). The function receives the variables start and end, and returns a list of squares of consecutive numbers between start and end inclusively. For example, squares(2, 3) should return [4, 9].

Complete the code to iterate through the keys and values of the car_prices dictionary, printing out some information about each one.

Taylor and Rory are hosting a party. They sent out invitations, and each one collected responses into dictionaries, with names of their friends and how many guests each friend is bringing. Each dictionary is a partial list, but Rory’s list has more current information about the number of guests. Fill in the blanks to combine both dictionaries into one, with each friend listed only once, and the number of guests from Rory’s dictionary taking precedence, if a name is included in both dictionaries. Then print the resulting dictionary.

Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters(“This is a sentence.”) should return {‘t’: 2, ‘h’: 1, ‘i’: 2, ‘s’: 3, ‘a’: 1, ‘e’: 3, ‘n’: 2, ‘c’: 1}.

What do the following commands return when animal = “Hippopotamus”?

What does the list “colors” contain after these commands are executed?

What do the following commands return?