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 - Python Tutorial
From the course: Programming Foundations: Data Structures
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
-
-
-
-
What is an array?2m 53s
-
Create a list in Python1m 48s
-
(Locked)
Retrieve data from a list in Python3m 39s
-
(Locked)
Mutate a list in Python2m 45s
-
(Locked)
Solution: Swap items2m 34s
-
(Locked)
Multidimensional lists in Python4m 36s
-
(Locked)
Tuples in Python2m 17s
-
(Locked)
Solution: Square items1m 52s
-
(Locked)
Search array-like structures3m 47s
-
(Locked)
Sort array-like structures3m 27s
-
(Locked)
Solution: Find the second smallest item2m 2s
-
(Locked)
When to use array-like structures1m 38s
-
-
-
-
-
-
-
-