Which is the most pythonic way and the fastest way (could be the same) to append many list together? For example, given the lists below:
a = [1, 2]
b = [3, 4]
c = [5, 6]
d = [7, 8]
we get one list:
combined = [1, 2, 3, 4, 5, 6, 7, 8]
In Python 3.5+, you can use the generic unpacking:
combined = [*a, *b, *c, *d]
or prior to Python 3.5+, you can use itertools.chain:
from itertools import chain
combined = list(chain(a, b, c, d))
I can't understand you
do you mean how to merge them?
for example
a = [1, 2]
b = [3, 4]
c = [5, 6]
d = [7, 8]
combined = a + b + c + d
so combined will be
[1, 2, 3, 4, 5, 6, 7, 8]
OR:
a = [1, 2]
b = [3, 4]
c = [5, 6]
d = [7, 8]
a.extend(b)
a.extend(c)
a.extend(d)
Now:
print(a)
Returns:
[1, 2, 3, 4, 5, 6, 7, 8]
Related
I am facing an issue given below and I want to separate the 0th element and the 1st element in two separate lists. for eg I have a list
a = [[1, 2], [3,4], [5,6], [7,8]]
I want two lists like:
a0 = [1,3,5,7]
a2 = [2,4,6,8]
Can anyone help me with this please?
You can use zip
a = [[1, 2], [3, 4], [5, 6], [7, 8]]
a = [[*x] for x in zip(*a)]
print(a[0], a[1]) # [1, 3, 5, 7] [2, 4, 6, 8]
You can do this -
a = [[1, 2],[3,4],[5,6],[7,8]]
a0 = []
a2 = []
for i in a:
a0.append(i[0])
a2.append(i[1])
print(a0)
print(a2)
Using a list comprehension:
a = [[1, 2],[3,4],[5,6],[7,8]]
a0 = [x[0] for x in a]
a2 = [x[1] for x in a]
print(a0) # [1, 3, 5, 7]
print(a2) # [2, 4, 6, 8]
a = [[1, 2],[3,4],[5,6],[7,8]]
a0 = []
a1 = []
for x in a:
a0.append(x[0])
a1.append(x[1])
use chain to flatten the list, then calculate the middle index, then split it into two lists from the middle index
In [1]: from itertools import chain
In [2]: a = [[1, 2],[3,4],[5,6],[7,8]]
In [3]: flat = list(chain.from_iterable(a))
In [4]: flat
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8]
In [5]: middle = len(flat) // 2
In [6]: first_half = flat[:middle]
In [7]: second_half = flat[middle:]
In [10]: first_half
Out[10]: [1, 2, 3, 4]
In [11]: second_half
Out[11]: [5, 6, 7, 8]
You can try below code
import numpy as np
a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
np.array(a).T.tolist()
gives as
[[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
I want to take multiple lists and know the values that appaer in these lists with the possibility of one or more of the lists being empty.
CASE 1:
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
c = []
d = [2, 3, 5]
Needed output: 5
CASE 2:
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5, 3]
c = [1, 3, 8]
d = []
Needed output: 3
Order doesn't matter.
I know I can use this if there are no empty lists (source 1 / source 2)
list(set(a) & set(b) & set(c) and set(d))
The problem occurs when one of the lists is empty.
Python version: 3.8
Lets use a list comprehension with set.intersection -
The list comprehension checks if the length of the list is greater than 0 and then uses it to find an intersection using set.intersection. The * operator unpacks this list of sets, to individual sets.
Case 1:
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
c = []
d = [2, 3, 5]
l = [a,b,c,d]
l = [set(i) for i in l if len(i)>0]
set.intersection(*l)
{5}
Case 2:
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5, 3]
c = [1, 3, 8]
d = []
l = [a,b,c,d]
l = [set(i) for i in l if len(i)>0]
set.intersection(*l)
{3}
You use filter() to remove empty lists and then convert your list to set() objects using map() and do the intersection as:
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
c = []
d = [2, 3, 5]
my_list = [a, b, c, d]
my_result = set.intersection(*map(set, filter(bool, my_list)))
# where `my_result` holds the value:
# {5}
I have the following lists
a=[1,2,3]
b=[4,5,6]
c=[a,b]
i need to combine both list a and b.
result should be like [1,2,3,4,5,6]
i tried with list comprehension
[x for x in i for i in c]
output
[3, 3, 4, 4, 5, 5]
How can i get the result as [1,2,3,4,5,6] using list comprehension.
You can just do:
a + b
If you must use list comprehension:
In [10]: a = [1, 2, 3]
In [11]: b = [4, 5, 6]
In [12]: c = [a, b]
In [13]: [j for i in c for j in i]
Out[13]: [1, 2, 3, 4, 5, 6]
Use itertools.chain.
import itertools
a=[1,2,3]
b=[4,5,6]
c = list(itertools.chain(a, b))
You are concatenating, use + to do so:
c = a + b
If you are concatenating an arbitrary number of lists, use itertools.chain.from_iterable():
from itertools import chain
list_of_lists = [a, b]
c = list(chain.from_iterable(list_of_lists))
Note that if all you need to do is iterate over the concatenation result, you can leave of the list() call altogether.
Do not use sum() for this; that leads to quadratic behaviour as intermediate results are built for every element summed, which takes a full loop.
You can do it with + operation
a = [1, 2, 3]
b = [3, 4, 5]
c = a + b # Equal [1, 2, 3, 3, 4, 5]
Here are 3 different ways you can do it:
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=a+b
>>> c
[1, 2, 3, 4, 5, 6]
>>> c=[item for l in [a, b] for item in l]
>>> c
[1, 2, 3, 4, 5, 6]
>>> import itertools
>>> list(itertools.chain(*[a, b]))
[1, 2, 3, 4, 5, 6]
In other words, I want to accomplish something like the following:
a = [1, 2, 3, 7, 8]
b = [4, 5, 6]
# some magic here to insert list b into list a at index 3 so that
a = [1, 2, 3, 4, 5, 6, 7, 8]
You can assign to a slice of list a like so:
>>> a = [1, 2, 3, 7, 8]
>>> b = [4, 5, 6]
>>> a[3:3] = b
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>>
The [3:3] may look weird, but it is necessary to have the items in list b be inserted into list a correctly. Otherwise, if we were to assign to an index of a, list b itself would be inserted:
>>> a = [1, 2, 3, 7, 8]
>>> b = [4, 5, 6]
>>> a[3] = b
>>> a
[1, 2, 3, [4, 5, 6], 8]
>>>
I tried to find a docs link which explicitly mentions this behavior, but was unsuccessful (please feel free to add one if you can find it). So, I'll just say that doing a[3:3] = b tells Python to take the items in list b and place them in the section of list a represented by [3:3]. Moreover, Python will extend list a as necessary to accommodate this operation.
In short, this is just yet another awesome feature of Python. :)
Try using the sort method as follows:
>>> a = [1,2,3,7,8]
>>> b = [4,5,6]
>>> a = sorted(a+b)
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
I am trying to expand sublists within a list. I wrote it for one layer of sublists within the list. Is there a better way to code this so to scale for arbitrary number of nested lists? See example as follows:
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
def expand(x):
# expands a list of lists with no further sublists
a = []
for i in x:
# could also here do a += i and avoid the second for loop
for j in i:
a.append(j)
return a
print expand(c)
Returns the desired [1, 2, 3, 4, 5, 6]
To further clarify, I am wondering how to better scale for
`e = [c, a, b]' and further nested iterations.
c = [[1, 2, 3], [4, 5, 6]]
# first method
res = [x for lst in c for x in lst]
# second method
from itertools import chain
res = list(chain(*c))
Edit: he wants iteratively nested lists!
c = [[[1], [2, 3]], [4, 5], [[6, 7, 8], 9]]
def expand(lst):
try:
for a in lst:
for b in expand(a):
yield b
except TypeError:
yield lst
res = list(expand(c)) # => [1, 2, 3, 4, 5, 6, 7, 8, 9]
Use Recursion:
def flat_list(l):
for a in l:
if isinstance(a, list):
for x in flat_list(a):
yield x
else:
yield a
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
e = [c, a, b]
print list(flat_list(c))
print list(flat_list(e))
the output is:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
One solution:
def flatten(ls):
result = []
stack = [ls]
while stack:
if isinstance(stack[-1], list):
try: stack.append(stack[-1].pop(0))
except IndexError: stack.pop() # remove now-empty sublist
else:
result.append(stack.pop())
return result
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
e = [c, a, b]
print flatten(e)
Output:
[1, 2, 3, 4, 5, 6]
Or :
Using sum:
>>> e
[[[1, 2, 3], [4, 5, 6]], [1, 2, 3], [4, 5, 6]]
>>> sum(e[0], [])
[1, 2, 3, 4, 5, 6]
Using reduce:
>>> reduce(lambda x,y: x+y, e[0])
[1, 2, 3, 4, 5, 6]
>>>