Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: change elements position in a list of instances

I have a list that is made of class instances:

MyList = [<instance1>, <instance2>, <instance3>]

I would like to change the position of the third element, <instance3>, that should now stay in the position index = 1, so with the following output:

MyList = [<instance1>, <instance3>, <instance2>]

I have built a simple example that works:

a = [1,2]
b = [3,4]
c = [5,6]
d = [a,b,c]

The code above gives me the following print d output:

d = [[1, 2], [3, 4], [5, 6]]

I'm able to swap the elements (1) and (2) with the following method:

d.remove(c)
d.insert(c,1)

which gives me the following output (that is the one that I want):

d = [[1, 2], [5, 6], [3, 4]]

However, when I try to make the same with my list of instances, I get the following AttributeError:

AttributeError: entExCar instance has no attribute '__trunc__'

Someoene can tell me if I'm wrong in the method (example: you cannot use this technique with list of instances, you should rather do "this or that") or in the way I'm setting the code? The following script is the actual code I'm trying to run getting the error:

newElement = self.matriceCaracteristiques[kk1]    
self.matriceCaracteristiques.remove(newElement) 
self.matriceCaracteristiques.insert(newElement,nbConditionSortieLong)   

Thanks in advance.

EDIT: SOME DETAILS MORE

entExCar is the class which is being instatiating self.matriceCaracteristiques is the list I want to manipulate newElement is the element I want to remove from its original position (kk1) and put back into the new position (nbConditionSortieLong).

like image 557
Matteo NNZ Avatar asked Jan 22 '14 10:01

Matteo NNZ


2 Answers

First, I didn't get the error you mentioned.
Second, it seems that you made a mistake in using insert, should be insert(1, c) rather than insert(c, 1), see docs

>>> d = [[1, 2], [5, 6], [3, 4]]
>>> c = d[1]
>>> d.remove(c)
>>> d
[[1, 2], [3, 4]]
>>> d.insert(c, 1)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    d.insert(c, 1)
TypeError: 'list' object cannot be interpreted as an integer
>>> d.insert(1, c)
>>> d
[[1, 2], [5, 6], [3, 4]]
like image 55
laike9m Avatar answered Sep 21 '22 18:09

laike9m


What about

MyList.insert(index_to_insert,MyList.pop(index_to_remove))
like image 28
redg25 Avatar answered Sep 20 '22 18:09

redg25