I want to write a list comprehension that will have print an element out of an array every other element.
How do I do so?
array = [1,2,3,4,5,6,7,8,9]
output: 2
3
4
5
6
7
8
9
array = [1,2,3,4,5,6,7,8,9]
newarray = [array[i] for i in range(0, len(array), 2)]
print(newarray)
The result is [1, 3, 5, 7, 9].
The question is a bit unclear as to what the final use of the code is, and therefore what the best way to accomplish it is. But if you are wanting to select every second element out of a list, you can just use slice notation:
>>> array = [1,2,3,4,5,6,7,8,9]
>>> odd = array[::2]
>>> odd
[1, 3, 5, 7, 9]
>>> even = array[1::2]
>>> even
[2, 4, 6, 8]
This can be generalised to selecting every nth element by changing the step parameter, e.g., to select every third element:
>>> third = array[::3]
>>> third
[1, 4, 7]
"an element out of an array every other element" .. meaning print out every other element?
If you really want to use list comprehension, here are two, one to collect the even index entries, the other the odd in their respective lists which are then printed out.
evens = [elem for i, elem in enumerate(array) if not (i % 2)]
odds = [elem for i, elem in enumerate(array) if i % 2]
print evens # entries at even index value
[1, 3, 5, 7, 9]
print odds # entries at odd index values
[2, 4, 6, 8]
Related
['aba']['b']['c']
These above element came while iterating in a loop and I want to make a list which contains these elements. How can I achieve my goal?
Make an empty list and then append results to that list. For example:
loop = [1, 2, 3, 4, 5, 6]
endresult = []
for i in loop:
if i % 2 == 0:
endresult.append(i)
Output:
[2, 4, 6]
I have a list of lists with different sizes but I want to make them all the same length. For example, make them with length of 5 by padding with zeros if length less than 5 or cut the list if length is more than 5. For example, I have a list:
foo = [
[1, 2, 3],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5, 6, 7]]
result = [
[1, 2, 3, 0, 0],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5]]
Do you have an idea of optimal and fast solution, if the list of lists is large?
List comprehension
Make a fill list and use slicing to get the appropriate lengths.
n = 5
fill = [0] * n
result = [sublist[:n] + fill[len(sublist):] for sublist in foo]
result = []
for sublist in foo:
size = len(sublist)
result.append(sublist[:5] + [0]*(5 - size))
To perform this optimization, i sliced additional elements beyond n = 5, and replaced with 0 those not reaching n = 5 by checking how many elements they miss.
def listOptimization(foo, n):
# slicing foo to have n elements on all child elements of foo
for i in range(len(foo)):
foo[i] = foo[i][:n]
# optimizing
for i in range(len(foo)):
# check if foo child element is less than n
# if true, append to the list with 0 depending on how many
# elements to reach n
if len(foo[i])<n:
temp = n-len(foo[i])
for x in range(temp):
foo[i].append(0)
return foo
result = [[bar[i] if i<len(bar)else 0 for i in range(5)] for bar in foo]
there are 5 elements in a row, so for i in range(5), the exceed 5 will be discard. then assign value directly,if the length of each row is less than i, assign 0
Actually, I found a pretty fast solution for me. If you have an idea how to solve it without a for loop please post.
for row in foo:
while len(row) < 5:
row.append(0)
else:
row[:5]
Given that a list, has N elements. Suppose i represents the ith element of list_1 with all elements initially 0. Also there is a list:
a = [ 1 , 2 , 3, 4, ., . , N]
I need to increment elements in list_1 by 1, which are in the range [x-y , x+y] inclusive, where y is the ith element of list a.
I tried list comprehension, but could not come up with a possible way of doing it. I am new to python so I couldn't think about any other possible way!
Sample Input:
list_1 = [ 0, 0, 0, 0, 0]
a = [ 1, 2, 3, 4, 5]
Sample Output:
list_1 = [5, 5, 4, 4, 3]
Example: The problem asks to increment elements that fall in the given range i.e. say x-y= 0 and x+y = 4 , it means increment 0th, 1st, 2nd , 3rd and 4th element of the list.
I would like to know a way to get the desired list, and overcoming the errors.
I think this is what you are looking for. This will increment in the range of indices x-y to x+y.
list_1 = list(range(10))
def incList(ls, x, y):
return [e + 1 if x-y <= i <= x+y else e for i, e in enumerate(ls)]
print(incList(list_1, x=3, y=2))
print(incList(list_1, x=3, y=4))
Output:
[0, 2, 3, 4, 5, 6, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 8, 9]
You can use enumerate to check the index and manipulate the element value in a single list comprehension.
Alternatively, if you want to iterate from the x-yth element to the x+yth element, use x-y-1 <= i <= x+y-1 in the list comprehension instead.
EDIT:
The original question suggested that a copy of the list with incremented values is fine, but the comments suggest otherwise. In order to change the original list directly, we can make a small alteration to the function.
def incList(ls, x, y):
for i in range(max(0, x-y), min(len(ls), x+y+1)):
ls[i] += 1
As before, change x-y and x+y+1 to x-y-1 and x+y if desired.
What is the difference of this two list in python:
list1 = [1,2,3,4,5,6,7,8,9]
list2 = [[[[1,2,3,4,5,6,7,8,9]]]]
When I use type(list1) and type(list2), all come with list , but when I try to make some deal such as:
Using list1:
new_total=[]
for i in range(0,len(list1),3):
b=list1[i:i+3]
print(len(b))
output:
9
6
3
Using list2:
for i in range(0,len(list2),3):
b=list2[i:i+3]
print(len(b))
output:
1
Well the elements within list 2 are the first element of the list within a list within a list.
So they are both of type list, however in the first you are printing the length of three indexed values hence 3.
In the second for loop you are printing the length of the inner list within a list, that only has one element in it (another list, which contains a list that contains the list of numbers within that)
Basically you have embedded the list of numbers 4 fold as the first element
within the original list
replying for only to clarify these reponses , just to help you to understand (as a friend) , i'll give some exemples, that may help you:
list1 = [1,2,3,4,5,6,7,8,9]
list2 = [[[[1,2,3,4,5,6,7,8,9]]]]
print (list2[0][0][0][0])
print (list2[0][0][0])
print (list2[0][0])
print (list2[0])
print (list2)
Output:
1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[[1, 2, 3, 4, 5, 6, 7, 8, 9]]
[[[1, 2, 3, 4, 5, 6, 7, 8, 9]]]
[[[[1, 2, 3, 4, 5, 6, 7, 8, 9]]]]
I hope that's clear. Good luck!
list1 = [1,2,3,4,5,6,7,8,9]
list2 = [[[[1,2,3,4,5,6,7,8,9]]]]
list1 is a list.
list2 is a list of list of list of list.
len(list1) #will get you 9.
len(list2) #will get you 1.
You will either have to iterate into the final list inside list2 or somehow flatten it into a one dimensional list.
Hope this helps point you in the right direction without directly giving out the answer.
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 6 years ago.
I need to add the first three elements of a list then add the next three elements of a list and so forth. This is the code I have got so far:
def get_triple_sums_list(a_list):
new_list = []
for numbers in range(0,len(a_list)):
numbers = sum(a_list[:3])
new_list.append(numbers)
return new_list
if a_list == []:
return []
For the list:
[1, 5, 3, 4, 5, 2]
This in turn gives me the result:
[9]
I need to get
[9, 11]
If the remaining numbers is less than 3, it gives me the remainder of the sum ie,
[1, 6, 2, 4, 3]
Gives me
[9, 7]
And
[1, 6, 2, 4]
Give me
[9, 4]
Let's analyze your code!
def get_triple_sums_list(a_list):
new_list = []
for numbers in range(0,len(a_list)):
numbers = sum(a_list[:3]) #You should be using the variable
#numbers here somehow.
#^^^^^^^ - You are overwriting the for-loop index.
new_list.append(numbers)
return new_list #Why are you returning here? You should be
#appending to `new_list`.
if a_list == []:
return []
Here is the fixed code:
def get_triple_sums_list(a_list):
new_list = []
for index in range(0,len(a_list), 3): #Range takes a 3rd param!
total = sum(a_list[index:index+3])#Get all the elements from the
#index to index+3
new_list.append(total)
return new_list
UPDATE: It seems there's a shortening contest going on -- and I do not want to be left behind. Here's an ugly version I'd like to add to the list.
>>> a = [1,2,3,4,5,6,7,8]
>>> a += [0]*(len(a)%3) #For people who are too lazy to import izip_longest
>>> map(sum,zip(a[::3], a[1::3], a[2::3]))
[6, 15, 15]
I like SuperSaiyan's approach of explaining things, I'll be the one who shortens it a bit. You can get the same result with a single comprehension:
l = [1, 5, 3, 4, 5, 2]
n = 3
r = [sum(l[i:i+n]) for i in range(0, len(l), n)]
print(r)
[9, 11]
l[i:i+n] splits the list in even chunks of length 3 and sum takes care of adding these together. Using the for i in range(0, len(l), n) we dictate that this operation is to happen for ceil(len(l) / 3) times.
Just cuz I like to be different.
l = [1, 5, 3, 4, 5, 3, 42]
g = lambda l,s: [sum(l[i:i+s]) for i in range(0,len(l),s)]
print g(l,3)
#>> [9,12,42]
The other answer mentions the fault with your code. However do note that it's always easier to use a list comprehension in these cases.
>>> l = [1, 5, 3, 4, 5, 2]
>>> [sum(l[i:i+3]) for i in range(0,len(l),3)]
[9, 11]
It also works for un-mod-3 lists
>>> l = [1, 5, 3, 4, 5]
>>> [sum(l[i:i+3]) for i in range(0,len(l),3)]
[9, 9]
See What does "list comprehension" mean? How does it work and how can I use it? for more details about a list comprehension.
Here is a slightly different way of doing it using zip_longest from itertools (izip_longest in python2), it splits the list in three lists then zip them to get packs of three elements and finally sums the packs:
from itertools import zip_longest
a=[1, 6, 2, 4, 3]
b=zip_longest(a[0::3],a[1::3],a[2::3],fillvalue=0)
result=[sum(x) for x in b]
>>>[9, 7]
Alternatively, you may achieve it by using map() with lambda function as:
>>> my_list = [1, 5, 3, 4, 5, 2]
>>> list(map(lambda x: sum(my_list[x:x+3]), range(0, len(my_list), 3)))
[9, 11]