Pythonic Swap of 2 lists elements

I found that I have to perform a swap in python and I write something like this:

arr[first], arr[second] = arr[second], arr[first]

I suppose this is not so pythonic. Does somebody know how to do a swap in python more elegant?

EDIT: I think another example will show my doubts:

self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]

is this the only available solution for swap in python?


Asked by: Aida855 | Posted: 06-12-2021






Answer 1

a, b = b, a

Is a perfectly Pythonic idiom. It is short and readable, as long as your variable names are short enough.

Answered by: Julian379 | Posted: 07-01-2022



Answer 2

The one thing I might change in your example code: if you're going to use some long name such as self.memberlist over an over again, it's often more readable to alias ("assign") it to a shorter name first. So for example instead of the long, hard-to-read:

self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]

you could code:

L = self.memberlist
L[someindexA], L[someindexB] = L[someindexB], L[someindexA]

Remember that Python works by-reference so L refers to exactly the same object as self.memberlist, NOT a copy (by the same token, the assignment is extremely fast no matter how long the list may be, because it's not copied anyway -- it's just one more reference).

I don't think any further complication is warranted, though of course some fancy ones might easily be conceived, such as (for a, b "normal" indices >=0):

def slicer(a, b):
  return slice(a, b+cmp(b,a), b-a), slice(b, a+cmp(a,b), a-b)

back, forth = slicer(someindexA, someindexB)
self.memberlist[back] = self.memberlist[forth]

I think figuring out these kinds of "advanced" uses is a nice conceit, useful mental exercise, and good fun -- I recommend that interested readers, once the general idea is clear, focus on the role of those +cmp and how they make things work for the three possibilities (a>b, a<b, a==b) [[not for negative indices, though -- why not, and how would slicer need to change to fix this?]]. But using such a fancy approach in production code would generally be overkill and quite unwarranted, making things murkier and harder to maintain than the simple and straightforward approach.

Remember, simple is better than complex!

Answered by: Eric159 | Posted: 07-01-2022



Answer 3

It's difficult to imagine how it could be made more elegant: using a hypothetical built-in function ... swap_sequence_elements(arr, first, second) elegant? maybe, but this is in YAGGI territory -- you aren't going to get it ;-) -- and the function call overhead would/should put you off implementing it yourself.

What you have is much more elegant than the alternative in-line way:

temp = arr[first]
arr[first] = arr[second]
arr[second] = temp

and (bonus!) is faster too (on the not unreasonable assumption that a bytecode ROT_TWO is faster than a LOAD_FAST plus a STORE_FAST).

Answered by: Cherry312 | Posted: 07-01-2022



Answer 4

a, b = b, a is about as short as you'll get, it's only three characters (aside from the variable names).. It's about as Python'y as you'll get

One alternative is the usual use-a-temp-variable:

self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]

..becomes..

temp = self.memberlist[someindexB]
self.memberlist[someindexB] = self.memberlist[someindexA]
self.memberlist[someindexA] = temp

..which I think is messier and less "obvious"

Another way, which is maybe a bit more readable with long variable names:

a, b = self.memberlist[someindexA], self.memberlist[someindexB]
self.memberlist[someindexA], self.memberlist[someindexB] = b, a

Answered by: Miranda224 | Posted: 07-01-2022



Answer 5

I suppose you could take advantage of the step argument of slice notation to do something like this:

myarr[:2] = myarr[:2][::-1]

I'm not sure this is clearer or more pythonic though...

Answered by: Lyndon921 | Posted: 07-01-2022



Similar questions

python - Pythonic way of saying "if all of the elements in list 1 also exist in list 2"

I want to return true from the if statement only if all of the elements from list 1 also exist in list 2 (list 2 is a superset of list 1). What is the most pythonic way of writing this?


python - pythonic way to delete elements from a numpy array

This question already has answers here:


python - A Pythonic way to insert elements of a list into a list of lists?

This question already has answers here:


The most pythonic way to slice a Python list every 100 elements

This question already has answers here:


python - pythonic way to filter list for elements with unique length

I want to filter a list, leaving only first elements with unique length. I wrote a function for it, but I believe there should be a simpler way of doing it: def uniq_len(_list): from itertools import groupby uniq_lens = list(set([x for x, g in groupby(_list, len)])) all_goods = [] for elem in _list: elem_len = len(elem) try: good = uniq_lens.pop([i for i, x in enu...


python - Pythonic way to select elements of an array based on values?

I'm looking for a pythonic (1-line) way to extract a range of values from an array Here's some sample code that will extract the array elements that are >2 and &lt;8 from x,y data, and put them into a new array. Is there a way to accomplish this on a single line? The code below works but seems kludgier than it needs to be. (Note I'm actually working with floats in my application) import numpy as np x0 = ...


python - A pythonic way to use Lxml to find all elements of a certain type

I'm not very good with Lxml but thought a few of you might know how one can quickly get through the following task. See below... Specifically, I need to parse the XML to get the value of the name attribute in all of the category elements. For example: &lt;categories&gt; &lt;category name="Test"&gt; &lt;p&gt;test_1&lt;/p&gt; &lt;/category&gt; &lt;category name="Acme"&gt; &lt;p&gt;acme_1&lt;/...


python - The most Pythonic way to access elements of a dict

I'm calling an API multiple times and eventually writing the results to a CSV. I have the following code to extract data from a dict: city = data['property'][0]['address']['locality'] zip_code = data['property'][0]['address']['postal1'] county = data['property'][0]['area']['countrysecsubd'] condition = data['property'][0]['building']['construction']['condition'] roof = data['property'][0]['buil...


python - pythonic way to add elements to nested list

I have a nest list: listSchedule = [[list1], [list2], etc..]] I have another list and I want to append to each nested list the element of this list if the first element of each matches a string. I can do it but I wonder if there is a more 'pythonic' way, using list comprehension? index = 0; for row in listSchedule: if row[0] == 'Download': row[3] = myOtherL...


python - More pythonic way to parse some values from a few elements from a list?

Is there a more pythonic way to write this code? this field_split variable becomes part of a mysql statement. I need to reformat these 5 time fields using dateutil.parser.parse and make the field None if the timestamp value was empty in the incoming CSV file that i parsed in to field_split. [6],[7],[8],[9],[44] are the columns that are timestamps is this table. I feel like there sh...


python - Pythonic way to move elements from one list to another?

This question already has answers here:


python - Pythonic way of saying "if all of the elements in list 1 also exist in list 2"

I want to return true from the if statement only if all of the elements from list 1 also exist in list 2 (list 2 is a superset of list 1). What is the most pythonic way of writing this?


python - Pythonic way to extract elements from heapq

I am using a priority queue (heapq) with datetime.datetime as priority. What is the most pythonic way to extract a subset of element from this list if I have the startTime and endTime to search for. (I can not alter the original list, so I must create a new list and return, or return an iterator) Below is an example of what I have: &gt;&gt;&gt; impo...


python - pythonic way to delete elements from a numpy array

This question already has answers here:


python - A Pythonic way to insert elements of a list into a list of lists?

This question already has answers here:


python - Pythonic way of finding elements of list not returned by SQL query

I have a list of objects Foo which have a uniquely identifying key, foo_key. I query a MySQL database for all rows in the table FooData which are in my list of Foo objects: sql = "SELECT * FROM FooData where foo_key in ({})".format(",".join(str(obj.foo_key) for obj in foo_list)) foo_rows = sql_exec(sql).fetchall() What would be the most p...


python - Most pythonic way to find the maximum elements out of list of np.array?

I have a list of np.array, mya = [a0,...,an] (all of which have the same shape and dtype). Say ai has the shape ai = array[xi0,xi1,..,xim]. I want to get [max((a[i] for a in mya)) for i in range(m)] . For example, let x=np.array([3,4,5]), y=np.array([2,50,-1]) and z=np.array([30,0,3]) then for ...


The most pythonic way to slice a Python list every 100 elements

This question already has answers here:


python - pythonic way to filter list for elements with unique length

I want to filter a list, leaving only first elements with unique length. I wrote a function for it, but I believe there should be a simpler way of doing it: def uniq_len(_list): from itertools import groupby uniq_lens = list(set([x for x, g in groupby(_list, len)])) all_goods = [] for elem in _list: elem_len = len(elem) try: good = uniq_lens.pop([i for i, x in enu...


python - Pythonic way to select elements of an array based on values?

I'm looking for a pythonic (1-line) way to extract a range of values from an array Here's some sample code that will extract the array elements that are >2 and &lt;8 from x,y data, and put them into a new array. Is there a way to accomplish this on a single line? The code below works but seems kludgier than it needs to be. (Note I'm actually working with floats in my application) import numpy as np x0 = ...


python - A pythonic way to use Lxml to find all elements of a certain type

I'm not very good with Lxml but thought a few of you might know how one can quickly get through the following task. See below... Specifically, I need to parse the XML to get the value of the name attribute in all of the category elements. For example: &lt;categories&gt; &lt;category name="Test"&gt; &lt;p&gt;test_1&lt;/p&gt; &lt;/category&gt; &lt;category name="Acme"&gt; &lt;p&gt;acme_1&lt;/...


python - Is it pythonic for a function to return multiple values?

In python, you can have a function return multiple values. Here's a contrived example: def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also"). W...


python - A pythonic way to insert a space before capital letters

I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?


python - Is there a more Pythonic way to merge two HTML header rows with colspans?

I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to d...


python - What is the pythonic way to share common files in multiple projects?

Lets say I have projects x and y in brother directories: projects/x and projects/y. There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc. Those are minor common goodies, so I don't want to create a single package for them. Questions arise about the whereabouts of such files, possible changes to PYTHONPATH, proper way to import, etc. What is th...


python - Pythonic ways to use 'else' in a for loop

This question already has answers here:


python - pythonic way to compare compound classes?

I have a class that acts as an item in a tree: class CItem( list ): pass I have two trees, each with CItem as root, each tree item has some dict members (like item._test = 1). Now i need to compare this trees. I can suggest to overload a comparison operator for CItem: class CItem( list ): def __eq__( self, other ): # first compare items as lists if not list.__eq...


python - Pythonic URL Parsing

There are a number of questions about how to parse a URL in Python, this question is about the best or most Pythonic way to do it. In my parsing I need 4 parts: the network location, the first part of the URL, the path and the filename and querystring parts. http://www.somesite.com/base/first/secon...


list - Pythonic way to get some rows of a matrix

I was thinking about a code that I wrote a few years ago in Python, at some point it had to get just some elements, by index, of a list of lists. I remember I did something like this: def getRows(m, row_indices): tmp = [] for i in row_indices: tmp.append(m[i]) return tmp Now that I've learnt a little bit more since then, I'd use a list comprehension like this:


python - What is the Pythonic way to write this loop?

for jr in json_reports: jr['time_created'] = str(jr['time_created'])


python - How do you make this code more pythonic?

Could you guys please tell me how I can make the following code more pythonic? The code is correct. Full disclosure - it's problem 1b in Handout #4 of this machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab &amp; I'm using scipy ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top