Adding elements to List using a comprehension - python

Lets say I have a list:
List = [1,2,3,4,5]
I want to use a comprehension to output a list of lists for every element, let's say i, in "List" containing 1,2,...,i. So the comprehension would output:
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]
The same would work for a List of List = [1,3,5] where the output would be:
[[1],[1,2,3],[1,2,3,4,5]
I do not want to use any modules like numpy or itertools
Any help would me much appreciated!

Sure:
>>> [range(1, i+1) for i in List]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

Related

Quicker way to join multiple lists passed as args to a Python function?

So I have a function which takes a variable number of lists as an argument, then combines those lists into one single list:
def comb_lists(*lists):
sublist = []
for l in lists:
sublist.extend(l)
print(sublist)
>>> comb_lists([1, 2], [3, 4], [5, 6])
[1, 2, 3, 4, 5, 6]
And it works. But I was just wondering if there was a simpler solution? I tried a list comprehension using list unpacking, but that returned a SyntaxError:
def comb_lists(*lists):
sublist = [*l for l in lists]
>>> comb_lists([1, 2], [3, 4], [5, 6])
SyntaxError: iterable unpacking cannot be used in comprehension
Is there any neater or quicker way to do this?
EDIT: itertools looks really useful for this sort of thing. I'd be interested to know if there's any way of doing it that doesn't rely on imports though.
here is the simplest solution
result = sum(lists, [])
There's built-in function chain.form_iterable() in itertools module to do this:
>>> from itertools import chain
>>> my_list = [[1, 2], [3, 4], [5, 6]]
>>> list(chain.from_iterable(my_list))
[1, 2, 3, 4, 5, 6]
If you do not want to import any module, you can write nested list comprehension to achieve this as:
>>> my_list = [[1, 2], [3, 4], [5, 6]]
>>> [e for l in my_list for e in l]
[1, 2, 3, 4, 5, 6]

Nested list - create new nested list with indices as items

I would like to create a new nested list from an already existing nested list. This new list should include the indices+1 from the existing list.
Example:
my_list = [[20, 45, 80],[56, 29],[76],[38,156,11,387]]
Result:
my_new_list = [[1,2,3],[1,2],[1],[1,2,3,4]]
How can I create such a list?
save a python loop, force iteration of range (required for python 3) in a list comprehension, so it's faster than a classical double nested comprehension:
my_list = [[20, 45, 80],[56, 29],[76],[38,156,11,387]]
index_list = [list(range(1,len(x)+1)) for x in my_list]
There's a few ways to do this, but the first that comes to mind is to enumerate the elements with a starting index of 1 in a nested list comprehension.
>>> [[index for index, value in enumerate(sub, 1)] for sub in my_list]
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
Another solution could be:
new_list = [list(range(1,len(item)+1)) for item in my_list]
Here is are some simple solutions:
>>> lst = [[20, 45, 80],[56, 29],[76],[38,156,11,387]]
>>> out = [[x+1 for x,_ in enumerate(y)] for y in lst]
>>> out
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
>>>
>>>
>>> out = [[x+1 for x in range(len(y))] for y in lst]
>>> out
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
Using nested list comprehension
First you want a list with every number from 1 to the length of your sublist. There are several ways to do this with list comprehension.
For example
[i for i in range(1, len(sublist) + 1)]
or
[i + 1 for i in range(len(sublist))]
Second you want to do this for every sublist inside your my_list. Therefore you have to use nested list comprehension:
>>> my_list = [[20, 45, 80],[56, 29],[76],[38,156,11,387]]
>>> my_new_list = [[i+1 for i in range(len(sublist))] for sublist in my_list]
>>> my_new_list
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
Using list comprehension with range
Another way would be using the range built-in function as a generator for your sublists:
>>> [list(range(1, len(sublist) + 1)) for sublist in my_list]
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]
Using map with range
Or you can use the map built-in function
>>> list(map(
... lambda sublist: list(range(1, len(sublist) + 1)),
... my_list
... ))
[[1, 2, 3], [1, 2], [1], [1, 2, 3, 4]]

Python converting array values to separate array

I have a python array that looks like this: [1, 2, 3, 4, 5]
I want it to look like this: [[1], [2], [3], [4], [5]]
How do I go about doing this?
Thanks!
I assume you are talking about lists. This should work:
l = [1, 2, 3, 4, 5]
out = [[i] for i in l]
You can also do it like this using append method of list
list_a = [1,2,3,4,5]
new_list = []
for i in list_a:
new_list.append([i])

How do I make two different lists with the corresponding elements of the first list?

Suppose I have a list like this:
[[1, 2], [2, 3], [5, 4]]
What I want is two different lists from the above list with first element in one list and the second element in the other.
The result will look like this:
[1,2,5] and [2,3,4]
Is there any way to do it by using list splicing ?
Use zip() to pair up the elements of the input lists:
lista, listb = zip(*inputlist)
The * applies the elements in inputlist as separate arguments, as if you called zip() as zip([1, 2], [2, 3], [5, 4]). zip() takes the first element of each argument and returns those together, and then the second element, etc.
This produces tuples, not lists, really, but that's easy to remedy:
lista, listb = map(list, zip(*inputlist))
Demo:
>>> inputlist = [[1, 2], [2, 3], [5, 4]]
>>> zip(*inputlist)
[(1, 2, 5), (2, 3, 4)]
>>> lista, listb = map(list, zip(*inputlist))
>>> lista
[1, 2, 5]
>>> listb
[2, 3, 4]
How about use numpy array?
import numpy as np
np.array(myList).transpose()
# array([[1, 2, 5],
# [2, 3, 4]])
Or
np.array(myList)[:, 0]
# array([1, 2, 5])
np.array(myList)[:, 1]
# array([2, 3, 4])

Slicing list of lists in Python

I need to slice a list of lists:
A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
idx = slice(0,4)
B = A[:][idx]
The code above isn't giving me the right output.
What I want is: [[1,2,3],[1,2,3],[1,2,3]]
Very rarely using slice objects is easier to read than employing a list comprehension, and this is not one of those cases.
>>> A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
>>> [sublist[:3] for sublist in A]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
This is very clear. For every sublist in A, give me the list of the first three elements.
With numpy it is very simple - you could just perform the slice:
In [1]: import numpy as np
In [2]: A = np.array([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]])
In [3]: A[:,:3]
Out[3]:
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
You could, of course, transform numpy.array back to the list:
In [4]: A[:,:3].tolist()
Out[4]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
print [a[:3] for a in A]
Using list comprehension
you can use a list comprehension such as: [x[0:i] for x in A]
where i is 1,2,3 etc based on how many elements you need.
Either:
>>> [a[slice(0,3)] for a in A]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Or:
>>> [list(filter(lambda x: x<=3, a)) for a in A]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
I am new in programming and Python is my First Language. it's only 4 to 5 days only to start learning. I just learned about List and slicing and looking for some example I found your problem and try to solve it Kindly appreciate if my code is correct.
Here is my code
A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
print(A[0][0:3],A[1][0:3],A[1][0:3])

Categories

Resources