I have a list:
mylist = [1,2,3]
And I want to change the first element to the list, so a list inside a list. My first try:
mylist + mylist[1:]
gives me
[1, 2, 3, 2, 3] # not what I want
my second try
mylist[0]=mylist
gives me
[[...], 2, 3] # is this an infinite list?
Although I want
[[1,2,3], 2, 3]
Making a new list that contains the old one - mylist = [mylist] + mylist[1:] Putting a copy of the list into itself - mylist[0] = mylist[:] mylist[0] = mylist. copy()
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index. Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.
To change the index values we need to use the set_index method which is available in pandas allows specifying the indexes. where, inplace parameter accepts True or False, which specifies that change in index is permanent or temporary. True indicates that change is Permanent.
mylist[0] = mylist
is pointing to reference of the mylist. You can visualise it something like this
Every 1st element is having a list which is again having another list. And this continues.
So the solution to your problem is something like this
>>> mylist = [1,2,3]
>>> mylist[0] = mylist[:]
>>> mylist
[[1, 2, 3], 2, 3]
mylist[0] = mylist
gives you a list that contains itself - meaning mylist == mylist[0] == mylist[0][0] == mylist[0][0][0] == ...
. It sounds like that's not what you want.
From the output you give, you problem is better stated as either:
mylist = [mylist] + mylist[1:]
mylist[0] = mylist[:]
mylist[0] = mylist.copy()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With