Created by - Robert Kotaki
Working with ListsIntroductionIn this lesson, we will learn how to loop through an entire list using Python's for loop. Looping through a list enables us to perform the same action on each item in the list, making it efficient to work with lists of any length.Looping Through an Entire ListTo illustrate how to loop through a list, let's use an example of a list of magicians' names and print each name in the list using a for loop.pythonCopy codemagicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician) In the above code, we define a list of magicians' names and then loop through the list using a for loop. The for loop retrieves each name from the list, associates it with the variable magician, and then prints it to the console. This process is repeated for each name in the list.A Closer Look at LoopingWhen using a for loop, the set of steps is repeated once for each item in the list, no matter how many items are in the list. In the example above, the loop is repeated three times, once for each magician's name in the list.When writing a for loop, we can choose any name we want for the temporary variable that will be associated with each value in the list. However, it's helpful to choose a meaningful name that represents a single item from the list.Doing More Work Within a for LoopWe can perform any action on each item in the list using a for loop. For example, we can print a message to each magician in the list.pythonCopy codemagicians = ['alice', 'david', 'carolina'] for magician in magicians: print(f"{magician.title()}, that was a great trick!") In the above code, we add a personalized message to each magician in the list. The for loop retrieves each name from the list, associates it with the variable magician, and then prints a message to the console with the magician's name. This process is repeated for each name in the list.ConclusionIn this lesson, we learned how to loop through an entire list using Python's for loop. Looping through a list allows us to perform the same action on each item in the list, making it efficient to work with lists of any length. We also learned that we can perform any action on each item in the list using a for loop.
More detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
Making Numerical ListsIntroductionLists are useful for storing sets of numbers, such as high scores, positions in a game, or data for data visualizationsPython provides tools to work with lists of numbers efficientlyUsing the range() FunctionPython's range() function generates a series of numbersIt starts counting at the first value given and stops when it reaches the second value provided (which is not included in the output)Example:scssCopy codefor value in range(1, 5): print(value) Output: 1 2 3 4To include the second value in the output, adjust the end value by 1: range(1, 6) for 1 2 3 4 5To start the sequence at 0, pass only one argument to range(): range(6) for 0 1 2 3 4 5Using range() to Make a List of NumbersUse the list() function to convert the results of range() into a list of numbersExample:scssCopy codenumbers = list(range(1, 6)) print(numbers) Output: [1, 2, 3, 4, 5]range() can also skip numbers by passing a third argument as the step sizeExample:scssCopy codeeven_numbers = list(range(2, 11, 2)) print(even_numbers) Output: [2, 4, 6, 8, 10]Almost any set of numbers can be created with range()Example: Making a List of Square NumbersTo make a list of square numbers, loop through each value using range() and append the square of each value to a listExample:scssCopy codesquares = [] for value in range(1, 11): square = value ** 2 squares.append(square) print(squares) Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]To make the code more concise, append the square of each value directly to the list without using a temporary variableExample:scssCopy codesquares = [] for value in range(1, 11): squares.append(value ** 2) print(squares) Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Choose a method that makes your code easy to read and understand, then look for ways to make it more efficient
More detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
Simple Statistics with a List of NumbersIn this lecture, we will cover some basic statistical operations that can be performed on a list of numbers in Python. We will also introduce list comprehensions, a powerful tool for generating lists in Python.Finding Minimum, Maximum, and Sum of a List of NumbersTo find the minimum, maximum, and sum of a list of numbers, Python provides three built-in functions: min(), max(), and sum(). Here's an example:pythonCopy code# create a list of numbers digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] # find the minimum value print("Minimum value:", min(digits)) # find the maximum value print("Maximum value:", max(digits)) # find the sum of all values print("Sum of all values:", sum(digits)) Output:yamlCopy codeMinimum value: 0 Maximum value: 9 Sum of all values: 45 List ComprehensionsList comprehensions are a concise way to create lists in Python. They combine the for loop and the creation of new elements into one line of code.Here's an example that creates a list of squares using a list comprehension:pythonCopy code# create a list of squares using a list comprehension squares = [value**2 for value in range(1, 11)] # print the list of squares print(squares) Output:csharpCopy code[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] In the above example, the list comprehension is enclosed in square brackets, with the expression value**2 generating the squares of the values in the range 1 to 10. The for loop iterates over the range and feeds each value to the expression.List comprehensions can be used to generate lists with any kind of logic or operation. They are especially useful when working with large datasets, where concise and efficient code is required.To summarize, we have covered how to find the minimum, maximum, and sum of a list of numbers in Python using built-in functions, and how to use list comprehensions to generate new lists in a concise and efficient way.
More detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
Working with Part of a ListSlicing a ListTo work with a specific group of items in a list, Python provides a way to slice a list. Slicing a list is done by specifying the index of the first and last elements you want to work with, separated by a colon.Basic SlicingHere's an example of slicing a list to get the first three elements:pythonCopy codeplayers = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) Output:cssCopy code['charles', 'martina', 'michael'] Notice that the slice stops one index before the second index you specify.If you want the second, third, and fourth items in a list, you would start the slice at index 1 and end it at index 4:pythonCopy codeplayers = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[1:4]) Output:cssCopy code['martina', 'michael', 'florence'] Omitting the First IndexIf you omit the first index in a slice, Python automatically starts your slice at the beginning of the list:pythonCopy codeplayers = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[:4]) Output:cssCopy code['charles', 'martina', 'michael', 'florence'] Omitting the Second IndexA similar syntax works if you want a slice that includes the end of a list. For example, if you want all items from the third item through the last item, you can start with index 2 and omit the second index:pythonCopy codeplayers = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[2:]) Output:cssCopy code['michael', 'florence', 'eli'] Negative IndexingRecall that a negative index returns an element a certain distance from the end of a list. Therefore, you can output any slice from the end of a list. For example, if we want to output the last three players on the roster, we can use the slice players[-3:]:pythonCopy codeplayers = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[-3:]) Output:cssCopy code['michael', 'florence', 'eli'] Specifying a StepYou can include a third value in the brackets indicating a step. If a third value is included, this tells Python how many items to skip between items in the specified range. Here's an example that skips every other item in the slice:pythonCopy codeplayers = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[::2]) Output:cssCopy code['charles', 'michael', 'eli']
More detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
Looping Through a Slice:In Python, you can use a slice to loop through a subset of elements in a list. Slices are very useful in a number of situations, such as when working with data, creating games, or building web applications.Let's take a look at an example where we loop through the first three players in a list of players and print their names as part of a simple roster:pythonCopy codeplayers = ['charles', 'martina', 'michael', 'florence', 'eli'] print("Here are the first three players on my team:") for player in players[:3]: print(player.title()) In the example above, we use a slice to loop through only the first three names in the list players. The slice players[:3] includes all elements from the beginning of the list up to, but not including, the fourth element. This means that we loop through the first three elements in the list.When you run the code, you'll see the following output:sqlCopy codeHere are the first three players on my team: Charles Martina Michael Notice how the loop only prints the names of the first three players.Slices can also be useful in situations where you want to process data in chunks of a specific size. For example, you could use slices to process data in batches of 100 items at a time.Here's an example that shows how you could use a slice to get a player's top three scores:pythonCopy codescores = [75, 92, 85, 68, 79, 82, 91, 72, 78, 88] top_scores = sorted(scores, reverse=True)[:3] print("Here are the player's top three scores:") for score in top_scores: print(score) In this example, we create a list of scores and sort it in decreasing order using the sorted() function with the reverse=True parameter. We then use a slice to get only the first three elements in the sorted list, which correspond to the player's top three scores. Finally, we loop through the top three scores and print them out.When you run the code, you'll see the following output:cssCopy codeHere are the player's top three scores: 92 91 88 Slices can also be used to display information in a series of pages with an appropriate amount of information on each page. For example, you could use slices to display a list of blog posts with five posts per page.Overall, slices are a powerful tool in Python that allow you to work with subsets of lists or other iterable objects. They can be used in a variety of situations, including games, data processing, and web applications.
More detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
In Python, copying a list involves creating a new list with the same elements as the original list. It is important to note that we need to create a separate list object and not just a reference to the original list.Here's an example:In the code above, new_list is a copy of original_list.pythonCopy codemy_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] We can now modify each list independently without affecting the other list. Here's an example:In the code above, we add 'cannoli' to my_foods and 'ice cream' to friend_foods. When we print both lists, we can see that each list has the appropriate favorite foods.Here's an example:In the code above, new_list is not a copy of original_list. Instead, it is a reference to the same list as original_list. Therefore, when we modify original_list, new_list is also modified.
More detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
TuplesIntroductionTuples are a type of data structure in Python.They are similar to lists but they are immutable, which means their values cannot be changed.Tuples are defined using parentheses instead of square brackets.They are useful when you want to create a collection of values that should not be modified.Defining a TupleTo define a tuple, use parentheses instead of square brackets.Access individual elements in a tuple using their index, just like in a list.Here is an example of defining a tuple:pythonCopy codedimensions = (200, 50) This creates a tuple called dimensions with two values: 200 and 50.Accessing Elements in a TupleYou can access individual elements in a tuple using their index.Here is an example of accessing elements in a tuple:pythonCopy codedimensions = (200, 50) print(dimensions[0]) print(dimensions[1]) This will output:Copy code200 50 Modifying a TupleTuples are immutable, which means their values cannot be changed.If you try to modify a tuple, you will get a TypeError.Here is an example of trying to modify a tuple:pythonCopy codedimensions = (200, 50) dimensions[0] = 250 This will raise a TypeError with the message:phpCopy codeTypeError: 'tuple' object does not support item assignment Creating a Tuple with One ElementIf you want to create a tuple with only one element, you need to include a trailing comma.Here is an example of creating a tuple with one element:pythonCopy codemy_tuple = (3,) The trailing comma is necessary to differentiate the tuple from a regular value.Without the comma, Python will interpret (3) as just the number 3.ConclusionTuples are a useful data structure in Python for creating collections of values that should not be modified.They are defined using parentheses and are immutable.Access individual elements in a tuple using their index.If you try to modify a tuple, you will get a TypeError.Include a trailing comma when creating a tuple with only one element.
More detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
Looping Through All Values in a TupleIntroductionYou can loop over all the values in a tuple using a for loop in Python.This is similar to looping over values in a list.Looping Through a TupleTo loop through all the values in a tuple, use a for loop.Here is an example of looping through a tuple:pythonCopy codedimensions = (200, 50) for dimension in dimensions: print(dimension) This will output:Copy code200 50 The for loop iterates over each element in the tuple and assigns it to the variable dimension.The code inside the loop then executes once for each element in the tuple.ConclusionYou can loop over all the values in a tuple using a for loop in Python.The for loop iterates over each element in the tuple and assigns it to a variable.The code inside the loop then executes once for each element in the tuple.
More detailsPublished - Tue, 11 Apr 2023
Created by - Robert Kotaki
IntroductionAlthough you cannot modify a tuple, you can assign a new value to a variable that represents a tuple in Python.This means that you can effectively overwrite a tuple with a new tuple.Writing Over a TupleTo write over a tuple, simply assign a new tuple to the same variable.Here is an example of overwriting a tuple:pythonCopy codedimensions = (200, 50) print("Original dimensions:") for dimension in dimensions: print(dimension) dimensions = (400, 100) print("\nModified dimensions:") for dimension in dimensions: print(dimension) This will output:yamlCopy codeOriginal dimensions: 200 50 Modified dimensions: 400 100 The first four lines define the original tuple and print the initial dimensions.We then assign a new tuple to the variable dimensions and print the new values.Python does not raise any errors because reassigning a variable is valid.ConclusionAlthough you cannot modify a tuple, you can overwrite a tuple with a new tuple by assigning a new tuple to the same variable.Tuples are simple data structures that are useful when you want to store a set of values that should not be changed throughout the life of a program.
More detailsPublished - Tue, 11 Apr 2023
Sat, 15 Apr 2023
Sat, 15 Apr 2023
Sat, 15 Apr 2023
Write a public review