How to move array elements in python
A Show
codeforester 35.7k16 gold badges101 silver badges126 bronze badges answered Jan 27, 2010 at 20:46
4 What about just using
tobias_k 79.5k11 gold badges114 silver badges171 bronze badges answered Dec 5, 2011 at 20:20
JamgoldJamgold 1,7061 gold badge14 silver badges18 bronze badges 7 Numpy
can do this using the
answered Oct 13, 2012 at 10:57
RichardRichard 51.7k30 gold badges168 silver badges243 bronze badges 3 It depends on what you want to have happen when you do this:
You might want to change your:
to:
answered Jan 27, 2010 at 21:48
jcdyerjcdyer 18.2k5 gold badges41 silver badges48 bronze badges 4 Simplest way I can think of:
runDOSrun 9,6655 gold badges43 silver badges54 bronze badges answered Jul 8, 2014 at 12:15
ThijsThijs 3053 silver badges2 bronze badges 2 Just some notes on timing: If you're starting with a list,
So if you are starting with Just for the sake of illustration, here are some sample timings on 1M iterations: Methods which require type conversion:
List methods mentioned here:
Timing code used is below. collections.dequeShowing that creating deques from lists is O(n):
If you need to create deque objects: 1M iterations @ 6.853878974914551 seconds
If you already have deque objects: 1M iterations @ 0.12380790710449219 seconds
np.rollIf you need to create nparrays 1M iterations @ 27.558452129364014 seconds
If you already have nparrays: 1M iterations @ 6.0491721630096436 seconds
"Shift in place"Requires no type conversion 1M iterations @ 4.819645881652832 seconds
l.append(l.pop(0))Requires no type conversion 1M iterations @ 0.32483696937561035
answered Jul 4, 2017 at 9:12
PurrellPurrell 12k16 gold badges55 silver badges70 bronze badges 4 I also got interested in this and compared some of the suggested solutions with perfplot (a small project of mine). It turns out that Kelly Bundy's suggestion
performs very well for all shifts. Essentially, perfplot performs the shift for increasing large arrays and measures the time. Here are the results:
Code to reproduce the plot:
answered Jul 20, 2018 at 15:04
Nico SchlömerNico Schlömer 48.7k24 gold badges186 silver badges223 bronze badges 6 If you just want to iterate over these sets of elements rather than construct a separate data structure, consider using iterators to construct a generator expression:
answered Oct 29, 2012 at 15:34
Phil HPhil H 19.4k7 gold badges64 silver badges103 bronze badges This also depends on if you want to shift the list in place (mutating it), or if you want the function to return a new list. Because, according to my tests, something like this is at least twenty times faster than your implementation that adds two lists:
In fact, even adding a Various implementations with some timing at http://gist.github.com/288272 answered Jan 27, 2010 at 23:10
keturnketurn 4,7503 gold badges28 silver badges40 bronze badges 3 For an immutable implementation, you could use something like this:
dabuno 3433 silver badges4 bronze badges answered Feb 25, 2012 at 21:49
BittercoderBittercoder 11.4k9 gold badges57 silver badges76 bronze badges Possibly a ringbuffer is more suitable. It is not a list, although it is likely that it can behave enough like a list for your purposes. The problem is that the efficiency of a shift on a list is O(n), which becomes significant for large enough lists. Shifting in a ringbuffer is simply updating the head location which is O(1) answered Jan 27, 2010 at 21:59
John La RooyJohn La Rooy 286k51 gold badges358 silver badges498 bronze badges If efficiency is your goal, (cycles? memory?) you may be better off looking at the array module: http://docs.python.org/library/array.html Arrays do not have the overhead of lists. As far as pure lists go though, what you have is about as good as you can hope to do. answered Jan 27, 2010 at 20:47
recursiverecursive 81.9k32 gold badges147 silver badges236 bronze badges 0
I think you are looking for this:
answered Mar 25, 2014 at 9:46
1 Another alternative:
answered Apr 9, 2016 at 17:05
damiodamio 5,8513 gold badges35 silver badges55 bronze badges
For example, given
the function should return
For another example, given
the function should return Given
the function should return
RobC 20.8k20 gold badges66 silver badges74 bronze badges answered Nov 15, 2019 at 8:41
I take this cost model as a reference: http://scripts.mit.edu/~6.006/fall07/wiki/index.php?title=Python_Cost_Model Your method of slicing the list and concatenating two sub-lists are linear-time operations. I would suggest using pop, which is a constant-time operation, e.g.:
shanethehat 15.4k11 gold badges55 silver badges85 bronze badges answered Feb 21, 2012 at 22:32
herrfzherrfz 4,7283 gold badges25 silver badges37 bronze badges 2 I don't know if this is 'efficient', but it also works:
EDIT: Hello again, I just found a big problem with this solution! Consider the following code:
The shift_classlist() method executes the same code as my x.insert(0,x.pop())-solution, otherlist is a list indipendent from the class. After passing the content of otherlist to the MyClass.classlist list, calling the shift_classlist() also changes the otherlist list: CONSOLE OUTPUT:
I use Python 2.7. I don't know if thats a bug, but I think it's more likely that I missunderstood something here. Does anyone of you know why this happens? answered May 17, 2013 at 16:57
wese3112wese3112 931 gold badge1 silver badge6 bronze badges 2 The following method is O(n) in place with constant auxiliary memory:
Note that in python, this approach is horribly inefficient compared to others as it can't take advantage of native implementations of any of the pieces. answered Jun 11, 2015 at 12:19
DRayXDRayX 1,0232 gold badges12 silver badges19 bronze badges 2 I have similar thing. For example, to shift by two...
answered Jan 13, 2016 at 18:19
eyoeldefareeyoeldefare 1,9471 gold badge14 silver badges24 bronze badges I think you've got the most efficient way
answered Aug 23, 2017 at 21:17
john ktejikjohn ktejik 5,6874 gold badges49 silver badges53 bronze badges Jon Bentley in Programming Pearls (Column 2) describes an elegant and efficient algorithm for rotating an
This can be translated to Python as follows:
Demo:
answered Jul 1, 2018 at 16:47
Eugene YarmashEugene Yarmash 134k37 gold badges309 silver badges366 bronze badges I was looking for in place solution to this problem. This solves the purpose in O(k).
answered Dec 25, 2019 at 16:14
AnkitAnkit 474 bronze badges What is the use case? Often, we don't actually need a fully shifted array --we just need to access a handful of elements in the shifted array. Getting Python slices is runtime O(k) where k is the slice, so a sliced rotation is runtime N. The deque rotation command is also O(k). Can we do better? Consider an array that is extremely large (let's say, so large it would be computationally slow to slice it). An alternative solution would be to leave the original array alone and simply calculate the index of the item that would have existed in our desired index after a shift of some kind. Accessing a shifted element thus becomes O(1).
answered Oct 31, 2017 at 23:53
Following function copies sent list to a templist, so that pop function does not affect the original list:
Testing:
Output:
answered Dec 14, 2017 at 15:21
rnsornso 22.5k22 gold badges102 silver badges213 bronze badges For a list
Examples,
answered Aug 2, 2018 at 4:48
helcodehelcode 1,7101 gold badge11 silver badges29 bronze badges 2 I'm "old school" I define efficiency in lowest latency, processor time and memory usage, our nemesis are the bloated libraries. So there is exactly one right way:
answered Dec 26, 2020 at 0:35
Below is an efficient algorithm that doesn't require the use of any additional data structure: def rotate(nums: List[int], k: int):
answered Jan 3 at 14:01
How do you move values in an array?In this article, we will go through the ways to shift an element of an array in Java.. Use the for Loop and a temp Variable to Shift an Array in Java.. Use the skip() Method to Shift an Array in Java 8.. Use the Collections. rotate(List Related Article - Java Array.. How do you move items in a list in Python?In Python, the easiest way to shift values in a list is with the Python list pop(), insert(), and append() functions. You can also use the deque() data structure from the Python collections module to shift a list. You can also use list slicing to shift a list forward or backwards in Python.
How do I move an array to another array in Python?ALGORITHM: STEP 1: Declare and initialize an array. STEP 2: Declare another array of the same size as of the first one. STEP 3: Loop through the first array from 0 to length of the array and copy an element from the first array to the second array that is arr1[i] = arr2[i].
How do you move an element in an array in Numpy?If we want to right-shift or left-shift the elements of a NumPy array, we can use the numpy. roll() method in Python. The numpy. roll() method is used to roll array elements along a specified axis.
|