From the course: Programming Foundations: Data Structures

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Solution: Square items

Solution: Square items

- [Instructor] To square items in a given list, we'll need to access each item and perform an operation on it. Then we'll want to store the original value and its results in a new list containing tuple. Let's start by creating a list that'll store those resulting tuples. This will be the list we return at the end of the function. To populate this list, we'll loop through our input list and access each element. For each element x in the list, or lst, we'll perform the operation to compute it square. So that's x * x. And then we'll store both the original and squared values in a tuple. The original value is x, and to create the tuple, we'll use two parentheses. Then we'll append this to our result list using the append function. After the loop is finished, we return the result list, which now contains the two of the original values and their squared values. Now in Python, we can actually condense this logic even more using a comprehension. This line of code creates a new list defined by…

Contents