I'm not sure why I get an error saying index out of range when I test this function. Can anyone please help me fix this?
def intersect_lists(L1, L2):
'''(list, list) -> list
Return L1 with items not in L2 removed.
>>> intersect_lists([1, 2, 3, 4, 5, 6], [4, 2, 6])
[2,4,6]
'''
new_list = []
for item in range(len(L1)):
if L1[item] == L2[item]:
new_list.append(L1[item])
return new_list
Use list comprehension:
def intersect_lists(L1, L2):
return [i for i in L1 if i in L2]
However, your specific error is being caused by the fact that you are iterating over the length of L1, which will ultimately lead to an index error because the length of L1 is greater than L2.
Without list comprehension:
def intersect_lists(L1, L2):
final_list = []
for i in L1:
if i in L2:
final_list.append(i)
return final_list
Or Boolean And:
list(set(L1) & set(L2))
Related
I want to write a function that takes three lists of integers, l1, l2, and l3, and returns
a list of all tuples, where each tuple (a,b,c) is such that a is from l1, b is
from l2 and c is from l3 and a+b=c.
Expected Output:
[(2,5,7), (3,4,7), (3,5,8)]
The output I got:
None
Here is the code that I have written:
def threeList(l1, l2, l3):
result = []
for num in list3:
for x in list1:
for y in list2:
if x + y == num:
tuples = (x,y,num)
list_of_tuples = result.extend(tuples)
return list_of_tuples
list1 = [1,2,3]
list2 = [4,5]
list3 = [7,8]
threeList(list1, list2, list3)
Try this:
import itertools as it
list1 = [1,2,3]
list2 = [4,5]
list3 = [7,8]
[(x,y,x+y) for x,y in it.product(list1,list2) if x+y in list3]
which returns:
> [(2, 5, 7), (3, 4, 7), (3, 5, 8)]
itertools.product is a clean replacement for nested for loops.
extend is an in-place method which returns None.
Change your code to:
def threeList(l1, l2, l3):
result = []
for num in l3:
for x in l1:
for y in l2:
if x + y == num:
tuples = (x, y, num)
result.append(tuples)
return result
list1 = [1, 2, 3]
list2 = [4, 5]
list3 = [7, 8]
print(threeList(list1, list2, list3))
Output:
[(2, 5, 7), (3, 4, 7), (3, 5, 8)]
Explanation :
I used append instead of extend because we want the tuple tuples itself not the items inside it. Also I replaced the names list3, list1, list2 with l3, l1, l2 respectively because these are the actual values passed to the function, if your code works now is because list1, list2, list3 are exist in outside and those are referenced inside the function. Then after the loop finishes I return the result which is a list of tuples.
This was to fix your solution, but a better alternative solution is to use itertools modules like product in your situation.
Extend modifies the object itself. It does not return anything.
result.extend(tuples)
return result
Also note your code snippet is not working. So it is hard to spot your exact issue.
Did you make a typo?
Indentation wrong?
etc
I want to write a function add_list, which adds two lists adjacent elements.
E.g. l1 = [1, 2, 3], l2= [1,2,3] should give [2,4,6]. I am lost and not sure how to approach it using loops. Can someone help please?
You can iterate both the lists using zip and then use list comprehension on them
[x+y for x,y in zip(l1, l2)]
Sample run:
>>l1 = [1, 2, 3]
>>l2= [1,2,3]
>>[x+y for x,y in zip(l1, l2)]
[2, 4, 6]
Other possible solution is to iterate through the index (can be used in list comprehension as well)
result = []
for i in range(len(l1)):
result.append(l1[i] + l2[i])
Output:
>>result
[2, 4, 6]
The following code will add numbers in two given list provided that both have same number of elements
def add_list(a, b):
result = [] # empty list
# loop through all the elements of the list
for i in range(len(a)):
# insert addition into results
result.append(a[i] + b[i])
return result
l1 = [1, 2, 3]
l2 = [1, 2, 3]
print(add_list(l1, l2))
How to program greater no finder from 2 list with list comprehension in python3
l1 = [1,3,5,7]
l2 = [2,4,6,8]
new_lst = [ l1[i] for i in range(len(l1)) if l1[i] >= l2[i] else l2[i] ] #list comprehension
print(new_lst)
Just use zip to iterate through elements from both the lists at the same time
>>> l1 = [1,3,5,7]
>>> l2 = [2,4,6,8]
>>>
>>> new_lst = [x if x >= y else y for x,y in zip(l1,l2)]
>>> new_lst
[2, 4, 6, 8]
Here is one way to do it:
Use zip to get tuples of pairs of elements, iterate and get the maximum:
l1 = [1,3,5,7]
l2 = [2,4,6,8]
new_list = [max(l) for l in zip(l1, l2)]
print(new_list)
This outputs
[2, 4, 6, 8]
Use a for loop then append it to new_lst:
l1 = [1,3,5,7]
l2 = [2,4,6,8]
new_lst = []
for i in range(len(l1)):
if l1[i] >= l2[i]:
new_lst.append(l1[i])
else:
new_lst.append(l2[i])
print(new_lst)
Note: This answer present way to fix original code, it is not intended as best solution of given task. Your original code
l1 = [1,3,5,7]
l2 = [2,4,6,8]
new_lst = [ l1[i] for i in range(len(l1)) if l1[i] >= l2[i] else l2[i] ]
print(new_lst)
cause SyntaxError as you put ternary if in wrong place - at end, which is piece for simple if (used for filtering, that is dropping elements not fullfilling condition). Ternary if is used for this or that choice based on condition and when used in comprehension its usage is like:
l1 = [1,3,5,7]
l2 = [2,4,6,8]
new_lst = [l1[i] if l1[i] >= l2[i] else l2[i] for i in range(len(l1))]
print(new_lst)
Output:
[2, 4, 6, 8]
I have a nested list:
regions = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
I want to remove every list in this nested list which is contained in another one, i.e., [3,4] contained in [1,3,4] and [1,2,3] contained in [1,2,3,5], so the result is:
result = [[1,3,4],[1,2,3,5]]
So far I'm doing:
regions_remove = []
for i,reg_i in enumerate(regions):
for j,reg_j in enumerate(regions):
if j != i and list(set(reg_i)-set(reg_j)) == []:
regions_remove.append(reg_i)
regions = [list(item) for item in set(tuple(row) for row in regions) -
set(tuple(row) for row in regions_remove)]
And I've got: regions = [[1, 2, 3, 5], [1, 3, 4]] and this is a solution, but I'd like to know what's the most pythonic solution?
(sorry for not posting my entire code before, I'm a new to this...
Here is a solution with list comprehension and all() function :
nested_list = [[1,2,3],[3,4],[1,3,4],[1,2,3,5],[2,5]]
result = list(nested_list) #makes a copy of the initial list
for l1 in nested_list: #list in nested_list
rest = list(result) #makes a copy of the current result list
rest.remove(l1) #the list l1 will be compared to every other list (so except itself)
for l2 in rest: #list to compare
if all([elt in l2 for elt in l1]): result.remove(l1)
#if all the elements of l1 are in l2 (then all() gives True), it is removed
returns:
[[1, 3, 4], [1, 2, 3, 5]]
Further help
all() built-in function: https://docs.python.org/2/library/functions.html#all
copy a list: https://docs.python.org/2/library/functions.html#func-list
list comprehension: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
I'm definitely overlooking a simpler route, but this approach works
list comprehension
from itertools import product
l = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
bad = [i for i in l for j in l if i != j if tuple(i) in product(j, repeat = len(i))]
final = [i for i in l if i not in bad]
Expanded explanation
from itertools import product
l = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
bad = []
for i in l:
for j in l:
if i != j:
if tuple(i) in product(j, repeat = len(i)):
bad.append(i)
final = [i for i in l if i not in bad]
print(final)
[[1, 3, 4], [1, 2, 3, 5]]
I am new to python so apologies for the naive question. I have a list
l1 = [2, 4, 6, 7, 8]
and another list of tuples
l2 = [(4,6), (6,8), (8,10)]
I want to output a list l3 of size l1 that compares the value of l1 to the first co-ordinates of l2 and stores the second co-ordinate if the first co-ordinate is found in l1, else stores 0.
output :
l3 = [0, 6, 8, 0, 10]
I tired to do a for loop like:
l3 = []
for i in range(len(l1)):
if l1[i] == l2[i][0]:
l3.append(l2[i][1])
else:
l3.append(0)
but this doesn't work. It gives the error
IndexError: list index out of range
which is obvious as l2 is shorter than l1.
You can create a dictionary from l2:
l1 = [2,4,6,7,8]
l2 =[(4,6),(6,8),(8,10)]
new_l2 = dict(l2)
l3 = [new_l2.get(i, 0) for i in l1]
Output:
l3 = [0,6,8,0,10]
I would always use Ajax1234's solution instead, but I wanted to illustrate how I would approach it using a for-loop, as you intended:
l3 = []
for elem in l1:
pairs = list(filter(lambda x: x[0] == elem, l2))
l3.append(pairs[0][1] if pairs else 0)
An alternate approach would be using next() and a list comprehension instead of filter() and a for-loop. This one is far more efficient and readable:
l3 = [next((u[1] for u in l2 if u[0] == elem), 0) for elem in l1]