How can I compute the average number of a nested list in Python? - python-3.x

I have a list:
a = [[1,2,3],[4,5,6],[7,8,9]]
And I want the average of the 3rd element of each list: (3 + 6 + 9)
Which function should i create in order to do this??

It is always better to let others know what you have tried yourself when asking questions on Stackoverflow.
Anyway, try the below code:
def third_avg(a_list):
list_of_third = [i[2] for i in a_list]
return sum(list_of_third)/len(list_of_third)
print(third_avg([[1,2,3],[4,5,6],[7,8,9]]))
Output:
6.0
This function basically creates a new list with only the third values of the sublists. Then returns the average (sum of all elements/num of elements).

Related

Appending Elements From Left/Start of List/Array

I came across appending elements to array from left. and it has two solution
Solution 1:
List = [2,3,4,5,6]
List.insert(0,1) # Using insert
List = [1,2,3,4,5,6]
Solution 2:
List = [2,3,4,5,6]
[1] + List # Concatenation of array
List = [1,2,3,4,5,6]
I'm new to Python So please can any one explain the time complexity of both solution according to me both solution takes O(n) am I right or wrong?

for loop doesn't itterate through all the data? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
data = [1, 2, 3, 4, 5]
for x in data:
print(x)
if data.count(x) < 2:
data.remove(x)
Hello Guys,
so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.
When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?
While the from #Stef and #0x5453 are both relevant to your problem. The comment from #ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.
To answer your question, about what's going on here, let[s examine your code:
The first pass through the value of x is 1
You print the value of x
You then test to see if the number of occurrences of x is less than 2
Since the answer is yes, you proceed to remove the item from the list.
The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3
You print the value 3
You check to see if the count of 3 is less than 2
Since the count is less you remove that item from the list.
This process than continues
Simple solution, use filter()
Construct an iterator from those elements of iterable for which function returns true
it returns a list of the list items that the function returned true for.
example:
x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)
or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))
output is [1,1,2,2]

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)
Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)
lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

Python map vs List comprehension Time Complexity

a = [1,2,3,4,5]
All the integers in this array can be converted into strings individually in the following 3 ways.
1) Using Str
a=[1,2,3,4,5]
for i in range(len(a)):
a[i] = str(a[i])
print(type(a[0]))
2) Using Map
a=[1,2,3,4,5]
a = list(map(str,a))
print(type(a[0]))
3) Using List Comprehension
a=[1,2,3,4,5]
a = [str(i) for i in a]
print(type(a[0]))
Can I know what is the time complexity in all the 3 cases to find out which method is efficient? I am a bit confused about this.
Thanks in advance!

Editing the elements of a list in python 3

My question is kind of a two part question.
If you are given a list
numbers = [10, 20, 30, 100]
and you wish to edit every element inside the list by adding 10 to each element. How would I go about doing this? And are you able to do this without creating a separate list?
Similarly, if you are given a list such as:
words = ['hello', 'hey', 'hi']
and wish to change every letter h inside the list to another letter say 'r' would it be a similar algorithm as the last?
Because you said you don't want to create a new list, you can't use list comprehension or map function as #gcandal suggested. You can try this instead.
def update_list(l, fn):
for i in range(len(l)):
l[i] = fn(l[i])
update_list(numbers, lambda a: a + 10)
update_list(words, lambda s: s.replace('h', 'r'))
You can do it by applying map:
numbers_plus_ten = map(lambda number: number + 10, numbers)
Or using list comprehension:
numbers_plus_ten = [number + 10 for number in numbers]

Resources