I have a list in example li = [1,2,3,4,5,6,7,8]
now I want slice of list exapmle:
li[1:4] will give [2,3,4]
now I want the other part of list i.e [5,6,7,8,1]
so how can I get it pythonically.
Just add the first element to the end of the remaining elements from index 4 to the end
l1 = li[1:4]
l2 = li[4:] + [li[0]]
In [22]: li = [1,2,3,4,5,6,7,8]
In [23]: l1 = li[1:4]
In [24]: l2 = li[4:]+ [li[0]]
In [25]: l1
Out[25]: [2, 3, 4]
In [26]: l2
Out[26]: [5, 6, 7, 8, 1]
In two steps using extend:
l2 = li[4:]
In [30]: l2.extend([li[0]])
Out[31]: [5, 6, 7, 8, 1]
The simplest (not the most efficient) way is to take the same list twice and slice from that:
def circ_slice(a, start, length):
return (a * 2)[start:start+length]
a = [0, 1,2,3,4,5,6,7,8]
print circ_slice(a, 2, 4) # [2, 3, 4, 5]
print circ_slice(a, 7, 4) # [7, 8, 0, 1]
"tail + head" solutions require if statements if the start position is not known in advance.
Here's a more efficient version:
import itertools
def circ_slice(a, start, length):
it = itertools.cycle(a)
next(itertools.islice(it, start, start), None)
return list(itertools.islice(it, length))
itertools example ;)Try this:
l1 = li[1:4]
l2 = li[4:]+ [li[0]]
On a side note:
You may check itertools.cycle which can be used to get the result in an efficient way.
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely