Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: change the first element to the list itself

Tags:

python

list

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]
like image 994
rororo Avatar asked Sep 22 '18 09:09

rororo


People also ask

How do you change the 1st element in a list Python?

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()

How do you replace an item in a list in Python?

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.

How do I return the first element in a list?

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.

How do you change the index value in Python?

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.


2 Answers

mylist[0] = mylist is pointing to reference of the mylist. You can visualise it something like this enter image description here

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]
like image 130
argo Avatar answered Sep 19 '22 04:09

argo


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:

  • 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()
like image 26
Eric Avatar answered Sep 20 '22 04:09

Eric