Now I will try not to sound too harsh, but did you attempt to google the problem at hand before starting? Building habits in programming is important, but it is equally important to building upon existing code. A quck search gives me the following useful links here, here and here.
General comments
l = len(nums) - 1
This needs a better name. A good rule of thumb is to avoid single letter variables. Secondly this variable is only used once, and thus is not needed. As you could have done
for i in range(len(nums)-1):
which is just as clear. As mentioned the next part could be shortened to
diff = abs(nums[0] - nums[1])
Perhaps the biggest woopsie in your code is nums.pop(0)
for two reasons
- It modifies your original list. Assume you have calculated and the mean differences, but now want to access the first element in your list:
nums[0]
what happens?
- Secondly
pop
is an expensive operation, as it shifts the indices for every element in the list for every pop.
Luckily we are iterating over the indices so we can use them to avoid poping. Combining we get
for i in range(len(nums) - 1):
diff = abs(nums[i-1] - nums[i])
diff_list.append(diff)
However, this can be written in a single line if wanted as other answers have shown. zip
is another solution for a simple oneliner, albeit it should be slightly slower due to slicing. I do not know how important performance is to you, so zip might be fine
[abs(j - i) for i, j in zip(nums, nums[1:])]
If speed is important it could be worth checking out numpy
Improvements
Combining everything, adding hints and struct and a numpy version we get
import numpy as np
from typing import List
def element_difference_1(nums: List[int]) -> List[int]:
return [abs(j - i) for i, j in zip(nums, nums[1:])]
def element_difference_2(nums: List[int]) -> List[int]:
return [abs(nums[i + 1] - nums[i]) for i in range(len(nums) - 1)]
def mean_value(lst: List[int]) -> float:
return sum(lst) / len(lst)
def mean_difference(nums: List[int], diff_function, rounding: int = 1) -> None:
num_diffs = diff_function(nums)
mean = mean_value(num_diffs)
return round(mean, rounding)
def mean_difference_np(lst) -> float:
return np.mean(np.abs(np.diff(lst)))
if __name__ == "__main__":
nums = [3, 1, 2, 5, 1, 5, -7, 9, -8, -3, 3]
print(mean_difference(nums, element_difference_1))
print(mean_difference(nums, element_difference_2))
print(mean_difference_np(np.array(nums)))
datetime
when dealing with time. Feel free to post a follow up question if you want further comments on your particular implementation \$\endgroup\$