In this module, we'll cover four essential data structures: lists, dictionaries, sets, and tuples. These structures serve different purposes and can greatly enhance your ability to organize and manipulate data.
Let's start with lists, which allow you to store multiple values in a single variable. With lists, you can easily add, remove, or modify elements. They are perfect for storing collections of related items, like names or numbers. On the other hand, dictionaries excel at associating values with specific keys, making them ideal for tasks like mapping data or organizing configurations. They provide fast lookup times and enable efficient key-based operations.
Next up, we have sets, which are useful when dealing with unique elements or performing mathematical set operations. Sets automatically remove duplicates, making them great for eliminating repetition or finding common elements. Lastly, tuples offer an immutable and ordered collection of values. They are valuable when you need data integrity and want to ensure that elements remain unchanged.
Understanding these data structures will unlock a range of possibilities in your programming journey. Whether you're building applications, analyzing data, or solving complex problems, having a grasp of lists, dictionaries, sets, and tuples will prove invaluable. So, let's dive in and discover the strengths, weaknesses, and use cases of each structure to enhance your Python skills!
Lists are one of the most versatile and commonly used data structures in Python. They are ordered, mutable (changeable), and can hold any type of object. You can think of a list as a collection of elements enclosed in square brackets [], with each element separated by a comma.
Example:
fruits = ['apple', 'banana', 'orange']
Strengths:
Limitations:
Use Cases:
Dictionaries, also known as associative arrays or hash maps, are unordered collections of key-value pairs. They are enclosed in curly braces {} and use a colon : to separate keys and values. Dictionaries are mutable, meaning you can modify them after creation.
Example:
student = {'name': 'Alice', 'age': 20, 'major': 'Computer Science'}
Strengths:
Limitations:
Use Cases:
Sets are unordered collections of unique elements. They are defined by enclosing comma-separated elements in curly braces {} or by using the set() function. Sets don't allow duplicate values, and they automatically remove duplicates if present.
Example:
fruits = {'apple', 'banana', 'orange'}
Strengths:
Limitations:
Use Cases:
Tuples are ordered, immutable collections of elements enclosed in parentheses (). They are similar to lists but cannot be modified once created.
Example:
point = (3, 5)
person = ("Alice", 25, "Engineer")
Limitations:
Strengths:
Weaknesses:
Use Cases:
In Python, indexes refer to the positions of elements within a list. Each element in a list has a unique index that represents its location. Indexing in lists is zero-based, meaning the first element has an index of 0, the second element has an index of 1, and so on.
You can use indexes to access and retrieve specific elements from a list, modify elements, or perform various operations. Here's an explanation of how indexes work in lists, along with examples:
To access a specific element in a list, you can use square brackets [] with the desired index value. This allows you to retrieve the element at that particular position.
Example:
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # Output: "apple"
print(fruits[2]) # Output: “orange”
In this example, the element at index 0 is accessed using fruits[0], which returns the value "apple". Similarly, fruits[2] retrieves the element at index 2, giving the value "orange".
Since lists are mutable, you can modify elements by assigning new values to specific indexes.
Example:
numbers = [1, 2, 3, 4, 5]
numbers[2] = 10
print(numbers) # Output: [1, 2, 10, 4, 5]
In this example, the element at index 2 in the numbers list is modified from 3 to 10 using assignment. By specifying the index and providing a new value, you can update the list accordingly.
In addition to positive indexes, Python allows negative indexing, where the index value starts from the end of the list. The last element has an index of -1, the second-to-last element has an index of -2, and so on.
Example:
fruits = ["apple", "banana", "orange"]
print(fruits[-1]) # Output: "orange"
print(fruits[-2]) # Output: “banana”
In this example, negative indexes are used to access elements from the end of the list. fruits[-1] retrieves the last element, "orange", while fruits[-2] retrieves the second-to-last element, "banana".
When working with indexes, it's crucial to ensure they fall within the valid range of the list. Accessing an index that is outside the range of the list will result in an IndexError.
Example:
numbers = [1, 2, 3]
print(numbers[3]) # Raises IndexError: list index out of range
In this example, the index 3 is out of range for the numbers list, resulting in an IndexError.
Understanding indexes allows you to access, modify, and manipulate specific elements within a list. It is an essential concept for working effectively with lists in Python.
In Python, the append() function is used to add new items or elements to the end of a list. It allows you to dynamically expand a list by appending elements without explicitly specifying the index position. Here's how to use the append() function in Python, along with examples:
list_name.append(item)
fruits = ["apple", "banana", "orange"]
fruits.append("grape")
print(fruits) # Output: ["apple", "banana", "orange", "grape"]
In this example, the append() function is used to add the item "grape" to the fruits list. The element is added to the end of the list, extending the list by one element.
numbers = [1, 2, 3, 4, 5]
new_numbers = [6, 7, 8]
for num in new_numbers:
numbers.append(num)
print(numbers) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
In this example, the append() function is used within a loop to add multiple items from the new_numbers list to the numbers list. Each element in new_numbers is iterated over, and append() adds it to the end of the numbers list.
Note: It's important to remember that when using append(), the item provided as an argument is added as a single element, even if it is itself a list or any other iterable. If you want to add the individual elements of another iterable to a list, you may need to use techniques like list concatenation or the extend() method.
my_list = []
my_list.append(10)
my_list.append(20)
my_list.append(30)
print(my_list) # Output: [10, 20, 30]
In this example, an empty list my_list is created, and the append() function is used to add elements to it. Each call to append() adds a new item to the end of the list.
The append() function is a convenient way to add elements to the end of a list dynamically. It allows you to expand and modify lists by appending items without explicitly specifying the index position.
In Python, you can add items to a dictionary by assigning a value to a new or existing key. Dictionaries are mutable data structures that store key-value pairs, and adding items involves specifying the key and assigning a value to it. Here's how to add items to a dictionary in Python, along with examples:
fruits = {"apple": 5, "banana": 3}
fruits["orange"] = 2
print(fruits) # Output: {"apple": 5, "banana": 3, "orange": 2}
In this example, a dictionary named fruits is initially defined with two key-value pairs. To add a new item, the key "orange" is used, and its corresponding value 2 is assigned to it. The new key-value pair is added to the dictionary.
fruits = {"apple": 5, "banana": 3}
new_fruits = {"orange": 2, "grape": 4}
fruits.update(new_fruits)
print(fruits) # Output: {"apple": 5, "banana": 3, "orange": 2, "grape": 4}
In this example, the update() method is used to add multiple items from the new_fruits dictionary to the fruits dictionary. The update() method merges the key-value pairs from new_fruits into fruits, adding any new items and updating existing ones.
Adding items to a dictionary is a fundamental operation in Python. By assigning a value to a new or existing key, you can dynamically expand or modify the dictionary, making it a powerful data structure for storing and organizing data.
Here's how to modify elements in both lists and dictionaries using Python, along with examples for each.
Lists in Python are mutable, meaning you can change or modify their elements after creation. To modify an element in a list, you can directly access it using its index and assign a new value to it. Here's an example:
fruits = ["apple", "banana", "orange"]
fruits[1] = "grape"
print(fruits) # Output: ["apple", "grape", "orange"]
In this example, the element at index 1 in the fruits list, which is initially "banana", is modified to "grape" using assignment. By assigning a new value to the specific index, the list is updated accordingly.
Dictionaries in Python store key-value pairs, and to modify the value of a specific key in a dictionary, you can assign a new value to that key. Here's an example:
fruits = {"apple": 5, "banana": 3, "orange": 2}
fruits["banana"] = 7
print(fruits) # Output: {"apple": 5, "banana": 7, "orange": 2}
In this example, the value associated with the key "banana" in the fruits dictionary is modified. By assigning a new value of 7 to the key "banana", the value is updated in the dictionary.
Note: If the specified key already exists in the dictionary, the assigned value will replace the existing value associated with that key. If the key is not found in the dictionary, a new key-value pair will be created.
Both lists and dictionaries offer the flexibility to modify their elements, allowing you to update and manipulate data as needed within your programs.
In Python, there are several methods and techniques to remove items from a list. Here are the common approaches:
The remove() method removes the first occurrence of a specified value from the list.
Example:
fruits = ["apple", "banana", "orange"]
fruits.remove("banana")
print(fruits) # Output: ["apple", "orange"]
The pop() method removes and returns the item at a specific index from the list.
Example:
fruits = ["apple", "banana", "orange"]
removed_fruit = fruits.pop(1)
print(removed_fruit) # Output: "banana"
print(fruits) # Output: ["apple", "orange"]
The del statement can remove an item from a list using its index or remove a slice of items.
Example:
fruits = ["apple", "banana", "orange"]
del fruits[1]
print(fruits) # Output: ["apple", "orange"]
List comprehension or the filter() function can be used to create a new list without specific elements based on a condition.
Example:
fruits = ["apple", "banana", "orange"]
new_fruits = [fruit for fruit in fruits if fruit != "banana"]
print(new_fruits) # Output: ["apple", "orange"]
In Python, there are also various methods and techniques to remove items from a dictionary. Here are the common approaches:
The del statement can remove a key-value pair from a dictionary using the specified key.
Example:
fruits = {"apple": 5, "banana": 3, "orange": 2}
del fruits["banana"]
print(fruits) # Output: {"apple": 5, "orange": 2}
The pop() method removes and returns the value associated with a specific key from the dictionary.
Example:
fruits = {"apple": 5, "banana": 3, "orange": 2}
removed_value = fruits.pop("banana")
print(removed_value) # Output: 3
print(fruits) # Output: {"apple": 5, "orange": 2}
Dictionary comprehension can be used to create a new dictionary without specific key-value pairs based on a condition.
Example:
fruits = {"apple": 5, "banana": 3, "orange": 2}
new_fruits = {key: value for key, value in fruits.items() if key != "banana"}
print(new_fruits) # Output: {"apple": 5, "orange": 2}
Below you will find some important-to-know list methods, which will allow you to manipulate and do useful things with lists.
Returns the index of the first occurrence of a specified element in a list. Raises a ValueError if the element is not found.
fruits = ["apple", "banana", "orange"]
index = fruits.index("banana")
print(index) # Output: 1
Returns the number of occurrences of a specified element in a list.
fruits = ["apple", "banana", "orange", "banana"]
count = fruits.count("banana")
print(count) # Output: 2
Sorts the elements of a list in ascending order. The original list is modified in-place.
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]
Reverses the order of elements in a list. The original list is modified in-place.
fruits = ["apple", "banana", "orange"]
fruits.reverse()
print(fruits) # Output: ["orange", "banana", "apple"]
Returns a shallow copy of the list. The new list references the same elements as the original list.
fruits = ["apple", "banana", "orange"]
fruits_copy = fruits.copy()
print(fruits_copy) # Output: ["apple", "banana", "orange"]
Returns the number of elements in a list.
fruits = ["apple", "banana", "orange"]
length = len(fruits)
print(length) # Output: 3
Removes all elements from a list, making it empty.
fruits = ["apple", "banana", "orange"]
fruits.clear()
print(fruits) # Output: []
Returns the minimum value from a list. Works with lists of numbers or strings based on their natural order.
numbers = [3, 1, 4, 2]
minimum = min(numbers)
print(minimum) # Output: 1
Returns the maximum value from a list. Works with lists of numbers or strings based on their natural order.
numbers = [3, 1, 4, 2]
maximum = max(numbers)
print(maximum) # Output: 4
Here are some of the most common/useful dictionary methods, including examples of how to use them:
Returns a view object that contains the keys of the dictionary.
fruits = {"apple": 5, "banana": 3, "orange": 2}
keys = fruits.keys()
print(keys) # Output: dict_keys(["apple", "banana", "orange"])
Returns a view object that contains the values of the dictionary.
fruits = {"apple": 5, "banana": 3, "orange": 2}
values = fruits.values()
print(values) # Output: dict_values([5, 3, 2])
Returns a view object that contains key-value pairs as tuples.
fruits = {"apple": 5, "banana": 3, "orange": 2}
items = fruits.items()
print(items) # Output: dict_items([("apple", 5), ("banana", 3), ("orange", 2)])
Returns the value associated with a specified key. Allows specifying a default value if the key is not found.
fruits = {"apple": 5, "banana": 3, "orange": 2}
value = fruits.get("banana")
print(value) # Output: 3
value = fruits.get("mango", 0) # Default value if key is not found
print(value) # Output: 0
Updates the dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs.
fruits = {"apple": 5, "banana": 3}
new_fruits = {"orange": 2, "mango": 4}
fruits.update(new_fruits)
print(fruits) # Output: {"apple": 5, "banana": 3, "orange": 2, "mango": 4}
Removes all key-value pairs from the dictionary, making it empty.
fruits = {"apple": 5, "banana": 3, "orange": 2}
fruits.clear()
print(fruits) # Output: {}
Returns a shallow copy of the dictionary. The new dictionary references the same key-value pairs as the original dictionary.
fruits = {"apple": 5, "banana": 3, "orange": 2}
fruits_copy = fruits.copy()
print(fruits_copy) # Output: {"apple": 5, "banana": 3, "orange": 2}
Returns the number of key-value pairs in the dictionary.
fruits = {"apple": 5, "banana": 3, "orange": 2}
length = len(fruits)
print(length) # Output: 3
Checks if a specified key exists in the dictionary.
fruits = {"apple": 5, "banana": 3, "orange": 2}
if "banana" in fruits:
print("Banana is present!")
Creates a new dictionary with specified keys and a default value.
keys = ["apple", "banana", "orange"]
default_value = 0
fruits = dict.fromkeys(keys, default_value)
print(fruits) # Output: {"apple": 0, "banana": 0, "orange": 0}
No terms have been published for this module.
Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.
Skip to the Next QuestionTry out the following code in PyCharm:
import turtle
myturtle = turtle.Turtle()
wn = turtle.Screen().bgcolor("black")
myturtle.pensize(5)
# Create a list of colors
liColors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
# Create a variable for the radius of each
# circle, and start at 5
intRadius = 5
for strColor in liColors:
myturtle.color(strColor)
myturtle.circle(intRadius)
intRadius += 5
turtle.Screen().exitonclick()
The code above introduces a few fun new turtle abilities we haven’t played around with yet:
turtle.Screen().bgcolor allows us to change the color of the turtle’s screen.
turtle.pensize allows us to change the thickness of the lines drawn by the turtle.
Those are a lot of fun to play around with. Make sure you try out some different colors and pen widths so you have a feel for what’s possible there.
What you’ll see next is a line of code starting with “liColors”. This line creates a new variable, liColors, and sets to equal a new variable type - a list (sometimes called an array in programming). A list can be a collection of any type of data; strings, integers, floats, booleans and brace yourself for this — even lists. In this case, our list contains strings that are the names of colors. In the “Infinite Snowflakes” sandbox, we used something similar, and the program would randomly choose a color for each snowflake.
In this program, we are going to use the list to direct how our code is run. Specifically, we will use this list of colors in a “for” loop, where one at a time each color will be put into a variable (strColor), and used to determine the turtle’s color for that time through the loop. When the loop has gone through each time in the list in this way, it will move on to the next line of code after the loop’s block of indented code.
So, looking at each line of the loop’s code block, we have the following three lines:
turtle.color(strColor)
This line takes the current color from the list, which has been set as the value of strColor, and uses it to change the turtle’s color.
turtle.circle(intRadius)
This line draws a circle where the size of the circle is equal to intRadius.
intRadius += 5
After drawing the circle, this last line adds 5 to the current value of intRadius – so next time the loop’s code block is run, the circle will be drawn just a little bit larger. You can try changing this value to a larger or smaller number and see what happens.
Once you have spent some time playing around, you r challenge for this sandbox is to make the design your own. You can change the color list – try adding more colors, using fewer colors, or even creating some other pattern that you like. Also, instead of circles, try another design. For an added challenge, instead of (or in addition to) intRadius, create a variable or two that changes the size, angle, or distance between the designs made by each loop.
Use nested dictionaries and custom functions to create an employee database program that allows you to add and remove employee records. It should include name, salary, and position title information for each employee. You can take a look at the guide at learnbyexample.com for some help and direction for this work.
Here is the sample Fruit Stand Code covered in the class video:
dFruit = { "fr1":{"name":"Banana", "price":.57, "quant":30}, "fr2":{"name":"Apple", "price":.75, "quant":40}, "fr3":{"name":"Kiwi", "price":1.57, "quant":20} }
def addFruit(dMain): strId = input("Fruit ID: ") strName = input("Fruit Name: ") flPrice = float(input("Fruit Price: ")) intQuant = int(input("Fruit Quantity: "))
dTemp = {"name":strName, "price":flPrice, "quant":intQuant} dMain[strId] = dTemp return dMain def printFruit(dMain): for key in dMain: print(f"ID: {key}".ljust(10,".") + dMain[key]['name'].rjust(15,".")) def removeFruit(dMain): strId = input("What is the ID of the fruit to remove? ") del dMain[strId] return dMain
while True: print(" FRUIT STAND ".center(46,"#")) print("""\nOptions: 1. See Inventory
2. Add a Fruit 3. Remove a Fruit""") strChoice = input("What do you want to do? ")
if (strChoice == "1"): printFruit(dFruit) elif (strChoice == "2"): printFruit(dFruit)
addFruit(dFruit) elif (strChoice == "3"): printFruit(dFruit) removeFruit(dFruit) else: print("That's not a good choice:") strMore = input("Do you want to do anything else? (y/n) ")
if (strMore == "n"): break
Please submit the complete program as a .py file.