Loading...

Data Manipulation: Swapping Values, Calculating Averages, and Unnesting Lists


Published on July 8, 2023 by Pradeepchandra Reddy S C

Tags: Python, Programming


SQL Introduction


Introduction:

In this article, we will explore various Python code snippets that focus on data manipulation tasks. We will cover topics such as swapping values in a list, calculating the mean and median of a dataset, and unnesting nested lists. These examples will demonstrate how Python provides powerful functionality to handle data efficiently. Throughout the process, I gained insights into fundamental concepts of Lists.


Problem 1: Swapping Highest and Lowest Temperatures

To start, we are given a list of average daily temperatures over a week and asked to swap the highest and lowest temperatures in the list. By utilizing Python's built-in functions, we find the maximum and minimum temperatures, along with their respective indices. With this information, we perform the swap operation and print the updated list.


Problem 2: Calculating Mean and Median

Next, we explore measures of averages using a list of product prices. We calculate the mean by dividing the sum of the prices by the number of elements in the list. Then, we sort the list to find the median. Depending on whether the number of elements is odd or even, we determine the middle element(s) and compute the median accordingly. Finally, we compare the mean and median to determine which is greater.


Problem 3: Unnesting a Nested List

In this problem, we encounter a list of technology companies. However, the last three companies are nested within a sub-list. To eliminate the nesting, we use the pop() method to remove the sub-list and store it separately. Then, we concatenate the original list with the extracted sub-list to obtain the desired result. Alternatively, we can use the remove() and extend() methods to achieve the same outcome.


Conclusion:

This article presented Python code snippets for various data manipulation tasks. We learned how to swap values in a list by finding the maximum and minimum elements and their respective indices. We also explored the calculation of mean and median for a dataset, showcasing Python's ability to handle mathematical operations efficiently. Lastly, we examined how to unnest a nested list by extracting the sub-list and merging it with the original list. These examples demonstrate the versatility and power of Python in handling and manipulating data effectively.