Add integers to specific items in a list in python? - python

I would like to add some integer to a range of items in a list in python.
I know that this is correct if you want to add an integer to every item in a list:
A = 2
B = 5
C = 6
mylist = [1,2,3,4,5,6,7,8]
mylist[:] = [i+C for i in mylist]
print mylist
but I would like to add C to items A through B. so that instead of resulting in this list:
mylist = [7,8,9,10,11,12,13,14]
I would get this list:
mylist = [1,2,*9*,*10*,*11*,*12*,7,8]
is there a way to do this?
Thanks

Assign to a slice of the list:
>>> A = 2
>>> B = 5
>>> C = 6
>>> mylist = [1,2,3,4,5,6,7,8]
>>> mylist[A:B+1] = [i+C for i in mylist[A:B+1]]
>>> mylist
[1, 2, 9, 10, 11, 12, 7, 8]
>>>

for i in range(A, B+1):
mylist[i] += C

In addition to #iCodez answer, if you don't want to modify the original, you can use if-else
A = 2
B = 5
C = 6
oldlist = [1,2,3,4,5,6,7,8]
mylist = [x+C if A <= i <= B else x for i, x in enumerate(oldlist)]

mylist[A:B+1] = [i+C for i in mylist[A:B+1]]

Related

How to check whether an element in list is in another list and at which index? [duplicate]

This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 1 year ago.
Let's say I have two lists
a = [1,2,3,4]
b = [5,9,1,2]
and I want to get the indices of every element in list b when an element of list a is in there. In this example, the result should be a list c containing all indices in b
c = [2,3]
1 in list a is on index 2 in b
2 in list a is on index 3 in b
Thanks in advance!!
[index for (index, item) in enumerate(b) if item in a]
output
[2, 3]
Use this:
c = [b.index(x) for x in a if x in a and x in b]
c
Output:
[2, 3]
I would solve that this way:
a = [1, 2, 3, 4]
b = [5, 9, 1, 2]
b_d = {b[i]: i for i in range(len(b))}
result = [b_d[v] for v in a if v in b_d]
print(result)
Using a set will make the inclusion check faster:
set_a = set(a)
c = [i for i, x in enumerate(b) if x in set_a]
You could simply iterate over the first list, then check if the item is inside the second list, if yes then append the index to your new list c:
a = [1,2,3,4]
b = [5,9,1,2]
c = []
for item in list_a:
if item in list_b:
c.append(list_b.index(item))
print(c)
Or use a list comprehension:
[list_b.index(item) for item in list_a if item in list_b]

Comparing two lists and making new list

So lets say I have two lists a=[1,2,3,4,5,6] and b=[2,34,5,67,5,6] I want to create a third list which will have 1 where elements are different in a and b and 0 when they are same, so above would be like c=[1,1,1,1,0,0]
You can zip the lists and compare them in a list comprehension. This takes advantage of the fact that booleans are equivalent to 1 and 0 in python:
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
[int(m!=n) for m, n, in zip(a, b)]
# [1, 1, 1, 1, 0, 0]
Try a list comprehension over elements of each pair of items in the list with zip:
[ 0 if i == j else 1 for i,j in zip(a,b) ]
Iterating with a for loop is an option, though list comprehension may be more efficient.
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
c=[]
for i in range(len(a)):
if a[i] == b[i]:
c.append(0)
else:
c.append(1)
print(c)
prints
[1, 1, 1, 1, 0, 0]
If you will have multiple vector operations and they should be fast. Checkout numpy.
import numpy as np
a=[1,2,3,4,5,6]
b=[2,34,5,67,5,6]
a = np.array(a)
b = np.array(b)
c = (a != b).astype(int)
# array([1, 1, 1, 1, 0, 0])
idk if this is exactly what youre loocking for but this should work:
edidt: just found out that Joe Thor commented almost the exact same a few minutes earlier than me lmao
a = [1, 2, 3, 4, 5, 6]
b = [2, 34, 5, 67, 5, 6]
results = []
for f in range(0, len(a)):
if a[f] == b[f]:
results.append(0)
else:
results.append(1)
print(results)
This can be done fairly simply using a for loop. It does assume that both lists, a and b, are the same length. An example code would like something like this:
a = [1,2,3,4,5,6]
b = [2,34,5,67,5,6]
c = []
if len(a) == len(b):
for i in range(0,len(a)):
if(a[i] != b[i]):
c.append(1)
else:
c.append(0)
This can also be done using list comprehension:
a = [1,2,3,4,5,6]
b = [2,34,5,67,5,6]
c = []
if len(a) == len(b):
c = [int(i != j) for i,j in zip(a,b)]
The list comprehension code is from this thread: Comparing values in two lists in Python
a = [1, 2, 3, 4, 5, 6]
b = [2, 34, 5, 67, 5,6]
c = []
index = 0
x = 1
y = 0
for i in range(len(a)): # iterating loop from index 0 till the last
if a[index]!= b[index]: # comapring each index
c.append(x) # if not equal append c with '1'
index += 1 # increment index to move to next index in both lists
else:
c.append(y)
index += 1
print(c)
This should work for two lists of any type.
tstlist = ["w","s","u"]
lstseasons = ["s","u","a","w"]
lstbool_Seasons = [1 if ele in tstlist else 0 for ele in lstseasons]
Output: lstbool_Seasons = [1,1,0,1]
This is the first time I have posted anything, still figuring out how things work here, so please forgive faux pas...

nested loops and conditional checks in list comprehensions (python)

I'm currenty learning list comprehension in Python and I want to write a function that takes two lists, a and b, and returns all elements of a that are divisible by all elements of b.
The equivalent of this (not using list comprehension) would be:
a = [10, 5]
b = [5, 2]
c = []
d = True
for i in a:
for j in b:
if i % j != 0:
d = False
if d:
c.append(i)
return c
How can I do this with list comprehension?
I currently have [x for x in a for y in b if x % y == 0] but that only requires x to match one of the items in b, not all of them.
Try this one:
a = [10, 5]
b = [5, 2]
res = [x for x in a if all(x % y == 0 for y in b)]
for completion on #superb rain 's comment. Here is also an example for any(...):
res = [x for x in a if not any(x % y != 0 for y in b)]

Return of a procedure using list in python

I am trying to add the value that is listed only in list y into list x.
I know I can use x.append(e) rather than x = x + [e] but I want to use +.
However, I don't know why I cannot produce the desired result, meaning that I cannot change the list a.
This is my code:
def union(x,y):
for e in y:
if e not in x:
x = x + [e]
a = [1,2,3]
b = [2,4,6]
union(a,b)
print a
print b
The result is:
a = [1,2,3], b = [2,4,6]
My expected result of print a is [1,2,3,4,6].
Just modify your union function to return the list x:
def union(x,y):
for e in y:
if e not in x:
x = x + [e]
return x
Then you can call:
>>> a = union(a,b)
>>> a
[1, 2, 3, 4, 6]
A shorter approach (with your same logic) would be using list comprehension:
>>> a += [i for i in b if i not in a]
>>> a
[1, 2, 3, 4, 6]
And the super-pythonic:
>>> list(set(a) | set(b))
[1, 2, 3, 4, 6]
It's worth pointing out that Python has the set data type for exactly this purpose. And it supports a .union(otherset) method!

Updating list values with new values read - Python [duplicate]

This question already has answers here:
How do i add two lists' elements into one list?
(4 answers)
Closed 9 years ago.
I was't really sure how to ask this. I have a list of 3 values initially set to zero. Then I read 3 values in at a time from the user and I want to update the 3 values in the list with the new ones I read.
cordlist = [0]*3
Input:
3 4 5
I want list to now look like:
[3, 4, 5]
Input:
2 3 -6
List should now be
[5, 7, -1]
How do I go about accomplishing this? This is what I have:
cordlist += ([int(g) for g in raw_input().split()] for i in xrange(n))
but that just adds a new list, and doesn't really update the values in the previous list
In [17]: import numpy as np
In [18]: lst=np.array([0]*3)
In [19]: lst+=np.array([int(g) for g in raw_input().split()])
3 4 5
In [20]: lst
Out[20]: array([3, 4, 5])
In [21]: lst+=np.array([int(g) for g in raw_input().split()])
2 3 -6
In [22]: lst
Out[22]: array([ 5, 7, -1])
I would do something like this:
cordlist = [0, 0, 0]
for i in xrange(n):
cordlist = map(sum, zip(cordlist, map(int, raw_input().split())))
Breakdown:
map(int, raw_input().split()) is equivalent to [int(i) for i in raw_input().split()]
zip basically takes a number a lists, and returns a list of tuples containing the elements that are in the same index. See the docs for more information.
map, as I explained earlier, applies a function to each of the elements in an iterable, and returns a list. See the docs for more information.
cordlist = [v1+int(v2) for v1, v2 in zip(cordlist, raw_input().split())]
tested like that:
l1 = [1,2,3]
l2 = [2,3,4]
print [v1+v2 for v1, v2 in zip(l1, l2)]
result: [3, 5, 7]
I would go that way using itertools.zip_longest:
from itertools import zip_longest
def add_lists(l1, l2):
return [int(i)+int(j) for i, j in zip_longest(l1, l2, fillvalue=0)]
result = []
while True:
l = input().split()
print('result = ', add_lists(result, l))
Output:
>>> 1 2 3
result = [1, 2, 3]
>>> 3 4 5
result = [4, 6, 8]
More compact version of #namit's numpy solution
>>> import numpy as np
>>> lst = np.zeros(3, dtype=int)
>>> for i in range(2):
lst += np.fromstring(raw_input(), dtype=int, sep=' ')
3 4 5
2 3 -6
>>> lst
array([ 5, 7, -1])

Categories