I am writing code about two lists and the sum element without using the sum function. So I need to return the sum of its elements. How do I define a list c with the total number of list a and b
The code below is what I already tried.
def add(list_a, list_b):
list_a = [1, 2, 3, 4, 5]
list_b = [1, 2, 3, 4, 5]
list_c = []
for i in range (0,5):
list_c.append(list_a[i]+second[i])
print (list_c)
The error code:
File "sum.py", line 7, in
list_c.append(list_a[i]+second[i])
NameError: name 'list_c' is not defined
You have an indentation problem. It should work if you indent the for block and the print statement. You also have a typo, second[i] should be list_b[i].
def add(list_a, list_b):
list_c = []
for i in range(0,5):
list_c.append(list_a[i]+list_b[i])
return(list_c)
list_a = [1, 2, 3, 4, 5]
list_b = [1, 2, 3, 4, 5]
print(add(list_a, list_b))
# [2, 4, 6, 8, 10]
A really short way to write this would be:
print([x+y for x,y in zip(list_a, list_b)])
It only works when the lists have the same length.
There are two issues. First, you don't need to define your lists inside a function, and secondly you were referencing the second list as second instead of list_b. The below is all you need:
list_a = [1, 2, 3, 4, 5]
list_b = [1, 2, 3, 4, 5]
list_c = []
for i in range(0, 5):
list_c.append(list_a[i] + list_b[i])
print (list_c)
Alternatively if you want to use it as a reusable function then you can move your loop logic into the function itself and pass the lists as parameters:
def add(list_a, list_b):
summed_list = []
for i in range(0, 5):
summed_list.append(list_a[i] + list_b[i])
return summed_list
summed = add([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
print(summed)
You might use map in order to achieve that following way:
list_a = [1, 2, 3, 4, 5]
list_b = [1, 2, 3, 4, 5]
def add(a,b):
return list(map(lambda x,y:x+y,list_a,list_b))
print(add(list_a,list_b))
Output:
[2, 4, 6, 8, 10]
Related
Note: I know there is probably an answer for this on StackOverflow already, I just can't find it.
I need to do this:
>>> lst = [1, 2, 3, 4, 5, 6]
>>> first_two = lst.magic_pop(2)
>>> first_two
[1, 2]
>>> lst
[3, 4, 5, 6]
Now magic_pop doesn't exist, I used it just to show an example of what I need. Is there a method like magic_pop that would help me to do everything in a pythonic way?
Do it in two steps. Use a slice to get the first two elements, then remove that slice from the list.
first_list = lst[:2]
del lst[:2]
If you want a one-liner, you can wrap it in a function.
def splice(lst, start = 0, end = None):
if end is None:
end = len(lst)
partial = lst[start:end]
del lst[start:end]
return partial
first_list = splice(lst, end = 2)
One option would be using slices
def func(lst: list, n: int) -> tuple:
return lst[:n], lst[n:]
lst = [1, 2, 3, 4, 5, 6]
first_two, lst = func(lst, 2)
print(lst)
# [3, 4, 5, 6]
Alternative, here is a kafkaesque approach using builtins:
def func(lst: list, i: int) -> list:
return list(map(lambda _: lst.pop(0), range(i)))
lst = list(range(10))
first_two = func(lst, 2)
print(first_two)
# [0, 1]
print(lst)
# [2, 3, 4, 5, 6, 7, 8, 9]
Try:
lst = [1, 2, 3, 4, 5, 6]
first_two, lst = lst[:2], lst[2:]
print(first_two)
print(lst)
Prints:
[1, 2]
[3, 4, 5, 6]
You can just create a lambda function to do this.
magic_pop = lambda x,y:(x[:y],x[y:]) if y<len(lst) else x
magic_pop(lst,3)
Out[8]: ([1, 2, 3], [4, 5, 6])
I had tried to make a list free of duplicates from another defined list using list comprehension as follows,
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list = []
my_list = [x for x in num if x not in my_list]
Upon calling my_list, I get back the same array
[1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
Could anyone kindly explain why this is happening?
Using set is more feasible than an if condition along with for loop:
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list = list(set(num))
print(my_list)
Ouput:
[1, 2, 3, 4, 5]
my_list isn't updated until after the comprehension is complete. During the comprehension my_list is an empty list.
If order matters the approach you want to take is:
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list = []
check_set = set()
for x in num:
if x not in check_set:
my_list.append(x)
check_set.add(x)
If order does not matter:
my_list = list(set(num))
you should try something like this :
In [99]: num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
...: my_list = []
In [100]: [my_list.append(item) for item in num if item not in my_list]
Out[100]: [None, None, None, None, None]
In [101]: my_list
Out[101]: [1, 2, 3, 4, 5]
The list is updated after the list comprehension process is complete because which the duplicates are still present.
You can try this list comprehension.
my_list=[]
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list=[my_list.append(x) or x for x in num if x not in my_list]
# [1,2,3,4,5]
If you don't care about the order.
my_lst=list(set(num))
From Python3.6 and above dictionaries store the insertion order or use collections.OrderedDict. So, you can try this.
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
my_list=list(dict.fromkeys(num).keys())
You can use seen set to keep track of the elements that are seen. If an element in in seen don't add it to my_list.
num = [1, 2, 2, 2, 3, 3, 4, 4, 4, 5]
seen=set()
my_list=[]
for x in num:
if x not in seen:
seen.add(x)
my_list.append(x)
my_list
# [1,2,3,4,5]
I have a list of dataframes with data duplicating in every next dataframe within list which I need to subtract between themselves
the_list[0] = [1, 2, 3]
the_list[1] = [1, 2, 3, 4, 5, 6, 7]
There are also df headers. Dataframes are only different in number of rows.
Wanted solution:
the_list[0] = [1, 2, 3]
the_list[1] = [4, 5, 6, 7]
Due to the fact that my list of lists, the_list, contains several dataframes, I have to work backward and go from the last df to first with first remaining intact.
My current code (estwin is the_list):
estwin = [df1, df2, df3, df4]
output=([])
estwin.reverse()
for i in range(len(estwin) -1):
difference = Diff(estwin[i], estwin[i+1])
output.append(difference)
return(output)
def Diff(li_bigger, li_smaller):
c = [x for x in li_bigger if x not in li_smaller]
return (c)
Currently, the result is an empty list. I need an updated the_list that contains only the differences (no duplicate values between lists).
You should not need to go backward for this problem, it is easier to keep track of what you have already seen going forward.
Keep a set that gets updated with new items as you traverse through each list, and use it to filter out the items that should be present in the output.
list1 = [1,2,3]
list2 = [1,2,3,4,5,6,7]
estwin = [list1, list2]
lookup = set() #to check which items/numbers have already been seen.
output = []
for lst in estwin:
updated_lst = [i for i in lst if i not in lookup] #only new items present
lookup.update(updated_lst)
output.append(updated_lst)
print(output) #[[1, 2, 3], [4, 5, 6, 7]]
Your code is not runnable, but if I guess what you meant to write, it works, except that you have one bug in your algorithm:
the_list = [
[1, 2, 3],
[1, 2, 3, 4, 5, 6, 7],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
]
def process(lists):
output = []
lists.reverse()
for i in range(len(lists)-1):
difference = diff(lists[i], lists[i+1])
output.append(difference)
# BUGFIX: Always add first list (now last becuase of reverse)
output.append(lists[-1])
output.reverse()
return output
def diff(li_bigger, li_smaller):
return [x for x in li_bigger if x not in li_smaller]
print(the_list)
print(process(the_list))
Output:
[[1, 2, 3], [1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7, 8, 9]]
[[1, 2, 3], [4, 5, 6, 7], [8, 9]]
One-liner:
from itertools import chain
l = [[1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]
new_l = [sorted(list(set(v).difference(chain.from_iterable(l[:num]))))
for num, v in enumerate(l)]
print(new_l)
# [[1, 2], [3], [4], [5]]
I'm working on a project and I need to repeat a list within a list a certain number of times. Obviously, L.append(L) just adds the elements again without creating separate lists. I'm just stumped on how to make the lists separate within the big list.
In short form, this is what I have:
L = [1,2,3,4,5]
If I wanted to to repeat it, say, 3 times so I'd have:
L = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
How do I achieve this? I'm looking for lists within the big list.
No need for any functions:
>>> L = [1,2,3,4,5]
>>> [L]*3
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
However, you should note that if you change one value in any of the lists, all the others will change because they reference the same object.
>>> mylist = [L]*3
>>> mylist[0][0] = 6
>>> print mylist
[[6, 2, 3, 4, 5], [6, 2, 3, 4, 5], [6, 2, 3, 4, 5]]
>>> print L
[6, 2, 3, 4, 5]
To avoid this:
>>> L = [1,2,3,4,5]
>>> mylist = [L[:] for _ in range(3)]
>>> mylist[0][0] = 6
>>> print L
[1, 2, 3, 4, 5]
>>> print mylist
[[6, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
Notice how L didn't change, and only the first list in mylist changed.
Thanks everyone in the comments for helping :).
What is the best way to do this:
>>> replace2([1, 2, 3, 4, 5, 6])
[2, 1, 4, 3, 6, 5]
def replace2inplace(lst):
lst[1::2], lst[::2] = lst[::2], lst[1::2]
This uses slice assignment and slice step sizes to swap every pair in the list around, in-place:
>>> somelst = [1, 2, 3, 4, 5, 6]
>>> replace2inplace(somelst)
>>> somelst
[2, 1, 4, 3, 6, 5]
Otherwise you could use some itertools tricks:
from itertools import izip, chain
def replace2copy(lst):
lst1, lst2 = tee(iter(lst), 2)
return list(chain.from_iterable(izip(lst[1::2], lst[::2])))
which gives:
>>> replace2([1, 2, 3, 4, 5, 6])
[2, 1, 4, 3, 6, 5]
with the list() call optional; if you only need to loop over the result the generator is enough:
from itertools import izip, chain, islice, tee
def replace2gen(lst):
lst1, lst2 = tee(iter(lst))
return chain.from_iterable(izip(islice(lst1, 1, None, 2), islice(lst2, None, None, 2)))
for i in replace2gen([1, 2, 3, 4, 5, 6]):
print i
where replace2gen() can take arbitrary iterators too.
Out-of-place version:
def replace2(lst):
return [x for pair in zip(lst[1::2], lst[::2]) for x in pair]
My choice:
x = range(1,7)
res = [e for e in itertools.chain(*zip(x[1::2],x[0::2]))]
>>> a = [1, 2, 3, 4, 5, 6]
>>> sum([[x+1,x] for x in a if x&1 == True],[])
[2, 1, 4, 3, 6, 5]
EDIT: Some further explanation was requested:
The code steps through each element in the list a and, if the element is odd (x&1 == True) it puts that element and the next element into a list in reverse order ([x+1,x]).
With out the sum(...,[]) function we would have
[[2, 1], [4, 3], [6, 5]]
The sum(...,[]) function removes the internal square brackets giving
[2, 1, 4, 3, 6, 5]
This can be done more generally by using the index of the list rather than its value:
>>> a = [1, 2, 3, 4, 5, 6]
>>> sum([[a[x],a[x-1]] for x in range(len(a)) if x&1 == True],[])
[2, 1, 4, 3, 6, 5]
However, this will remove the last element of the list if its length is not even.