excluding an internal element while slicing [duplicate] - python

This question already has answers here:
Understanding slicing
(38 answers)
Closed 7 years ago.
So I've got a list...
a = [1,2,3,4,5]
I can produce b without 5 by saying:
b = a[:-1]
How do I produce c without 3?
c = a[:2:]?

You would need to slice twice and concatenate the lists , Example -
c = a[:2] + a[3:] #2 being the index of element `3` in the array.
Demo -
>>> a = [1,2,3,4,5]
>>> a[:2] + a[3:]
[1, 2, 4, 5]

By adding two lists
>>> a = [1,2,3,4,5]
>>> c = a[:3-1] + a[3:] # Explicitly mentioned 3-1 to help understand better
>>> c
[1, 2, 4, 5]
An inplace way to remove
>>> a = [1,2,3,4,5]
>>> a.pop(3-1)
3
>>> a
[1, 2, 4, 5]

One method is to join the two list parts together as follows
a = [1,2,3,4,5]
c = a[:2] + a[3:]
c
[1,2,4,5]

You can also just pop the index out i.e.
>>> a = [1,2,3,4,5]
>>> a.pop(2)
>>> 3
>>> print(a)
[1,2,4,5]

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]

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!

List indexing in Python [duplicate]

This question already has answers here:
Python: filtering lists by indices
(7 answers)
Closed 8 years ago.
I have two lists a=[10,5,6,8] and b=[1,3]. How can I use the latter as a subscript of the former? I.e. I would like to extract the second and fourth element of a.
Put otherwise, in Matlab I would use
v = [16 5 9 4 2 11 7 14];
v([1 5 6]) % Extract the first, fifth, and sixth elements
>> ans =
16 2 11
How can I do the same in Python?
You can use operator.itemgetter to do it:
from operator import itemgetter
a=[10,5,6,8]
b=[1,3]
res = itemgetter(*b)(a)
# (5, 8)
You can use a list comprehension like so:
>>> a = [10, 5, 6, 8]
>>> b = [1, 3]
>>> [a[x] for x in b]
[5, 8]
>>>
numpy supports indexing with arrays, as well as a bunch of other array and matrix operations, in Matlab style. Consider using it for computationally intensive tasks:
In [1]: import numpy as np
In [2]: a = np.array([10,5,6,8])
In [3]: b = np.array([1,3])
In [4]: a[b]
Out[4]: array([5, 8])
l=[1 5 6]
v = [16 5 9 4 2 11 7 14];
[v[i] for i in l]
you can try like this
it can be explained like this
for i in l:
print v[i]
a=[10,5,6,8]
b=[1,3]
ex = [a[i] for i in b]
print(ex) # [5, 8]

what is the difference between a = x and a=x[:] in python [duplicate]

This question already has answers here:
What is the difference between list and list[:] in python?
(7 answers)
Closed 9 years ago.
I am trying to learn Python. Can someone please help me understand the difference between following two:
a = x vs a=x[:]
a = x creates a reference:
a = [2]
x = a
print id(a)
print id(x)
Produces:
39727240
39727240
So if you alter a then x would change too because they are the same objects
Whereas
a = x[:] creates a new object
a = [2]
x = a[:]
print id(a)
print id(x)
Produces:
41331528
39722056
But over here changing a doesn't alter x because they are different objects
Trying to explain:
>>> x = [1,2,3]
>>> a = x
>>> # a is reference to x - a[0] and x[0] are same variable
>>> a[0] = 4 # same as x[0]...
>>> print x # proof
[4, 2, 3]
>>> a = x[:] # a is copy of x
>>> a[2] = 5 # a[2] is not x[2]
>>> print x
[4, 2, 3]
>>> print a
[4, 2, 5]
>>>
In [648]: b = a
In [649]: b[0] = 2
In [650]: a
Out[650]: [2] <- a also changed
In [651]: b = a[:] <- Creating new object
In [652]: b[0] = 3
In [653]: b
Out[653]: [3]
In [654]: a
Out[654]: [2] <- a did not change

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