Adding an element to a nested python list - python

I am learning Python and am having trouble with lists. I want to create a list containing a nested list e.g. a = [1, [2]]. I then want to 'append' 4 to the nested list making a[1,[2,4]] and then insert 3 between [2,4] making a[1,[2, 3, 4]].
a.append(4) does [1,[2],4], I cannot find a way to achieve what I want.

Try:
>>> a = [1, [2]]
>>> a[-1].append(4)
>>> a
[1, [2, 4]]
>>> a[-1].insert(1, 3)
>>> a
[1, [2, 3, 4]]

Related

How to insert a list at a specific index?

I got a list
a=[1,2,3]
and a list of list
b=[[1,2],[3,4,5]]
and I want to insert a into b at index 1 so b becomes
b=[[1,2],[1,2,3],[3,4,5]]
How do I do that?If I use insert it won't work because I can only insert an item not a list?
EDIT:I realised insert can be used for lists as well.Thanks.
You can use list.insert which takes the index as the first argument
>>> a=[1,2,3]
>>> b=[[1,2],[3,4,5]]
>>> b.insert(1, a)
>>> b
[[1, 2], [1, 2, 3], [3, 4, 5]]
You can use list slicing:
b=[[1,2],[3,4,5]]
a = [1, 2, 3]
final_list = b[:1]+[a]+b[1:]
Output:
[[1, 2], [1, 2, 3], [3, 4, 5]]

Why does assignment to python type 'list' work? [duplicate]

Newbie with a question, so please be gentle:
list = [1, 2, 3, 4, 5]
list2 = list
def fxn(list,list2):
for number in list:
print(number)
print(list)
list2.remove(number)
print("after remove list is ", list, " and list 2 is ", list2)
return list, list2
list, list2 = fxn(list, list2)
print("after fxn list is ", list)
print("after fxn list2 is ", list2)
This results in:
1
[1, 2, 3, 4, 5]
after remove list is [2, 3, 4, 5] and list 2 is [2, 3, 4, 5]
3
[2, 3, 4, 5]
after remove list is [2, 4, 5] and list 2 is [2, 4, 5]
5
[2, 4, 5]
after remove list is [2, 4] and list 2 is [2, 4]
after fxn list is [2, 4]
after fxn list2 is [2, 4]
I don't understand why list is changing when I am only doing list2.remove(), not list.remove(). I'm not even sure what search terms to use to figure it out.
The reason this is happening can be found here:
mlist = [1,2,3,4,5]
mlist2 = mlist
the second statement "points" mlist2 to mlist (i.e., they both refer to the same list object) and any changes you make to one is reflected in the other.
To make a copy instead try this (using a slice operation):
mlist = [1,2,3,4,5]
mlist2 = mlist[:]
In case you are curious about slice notation, this SO question Python Lists(Slice method) will give you more background.
Finally, it is not a good idea to use list as an identifier as Python already uses this identifier for its own data structure (which is the reason I added the "m" in front of the variable names)
That's because both list and list2 are referring to the same list after you did the assignment list2=list.
Try this to see if they are referring to the same objects or different:
id(list)
id(list2)
An example:
>>> list = [1, 2, 3, 4, 5]
>>> list2 = list
>>> id(list)
140496700844944
>>> id(list2)
140496700844944
>>> list.remove(3)
>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 4, 5]
If you really want to create a duplicate copy of list such that list2 doesn't refer to the original list but a copy of the list, use the slice operator:
list2 = list[:]
An example:
>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 4, 5]
>>> list = [1, 2, 3, 4, 5]
>>> list2 = list[:]
>>> id(list)
140496701034792
>>> id(list2)
140496701034864
>>> list.remove(3)
>>> list
[1, 2, 4, 5]
>>> list2
[1, 2, 3, 4, 5]
Also, don't use list as a variable name, because originally, list refers to the type list, but by defining your own list variable, you are hiding the original list that refers to the type list. Example:
>>> list
<type 'list'>
>>> type(list)
<type 'type'>
>>> list = [1, 2, 3, 4, 5]
>>> list
[1, 2, 3, 4, 5]
>>> type(list)
<type 'list'>

How to append/remove multiple objects instances to/from a list Python?

im trying to append and remove multiple objects instances from a list in Python. However, I couldn't find a short way to do it and had to use to for cycles ... is there any compact way to do it ?
Append to list:
# Create objects
specialAgent.append(Boid(1))
specialAgent.append(Boid(2))
for i in range(2):
boids.append(specialAgent[-1-i])
Remove from list:
# Destroy objects
for i in range(len(specialAgent)):
boids.remove(specialAgent[i])
You could use slice assignment:
>>> L = [1, 2, 3]
>>> L[3:] = [4, 5, 6]
>>> L
[1, 2, 3, 4, 5, 6]
>>> L[-3:] = []
>>> L
[1, 2, 3]
You can also append multiple items to a list using the .extend() list method:
>>> L.extend([4, 5, 6])
>>> L
[1, 2, 3, 4, 5, 6]

Best Pythonic way to conditionally append lists

I'm sure this question has come up before, but I couldn't find an exact example.
I have 2 lists and want to append the second to the first, only of the values are not already there.
So far I have working code, but was wondering if there were a better, more "Pythonic" was of doing this:
>>> list1
[1, 2, 3]
>>> list2
[2, 4]
>>> list1.extend([x for x in list2 if x not in list1])
>>> list1
[1, 2, 3, 4]
EDIT
Based on comments made, this code does not satisfy adding only once, ie:
>>> list1 = [1,2,3]
>>> list2 = [2,4,4,4]
>>> list1.extend([x for x in list2 if x not in list1])
>>> list1
[1, 2, 3, 4, 4, 4]
How would I end up with only:
[1, 2, 3, 4]
If you want to maintain the order, you can use collections.OrderedDict like this
from collections import OrderedDict
from itertools import chain
list1, list2 = [1, 2, 3], [2, 4]
print list(OrderedDict.fromkeys(chain(list1, list2)))
# [1, 2, 3, 4]
If the order of the elements is not important, you can use the set like this
from itertools import chain
list1, list2 = [1, 2, 3], [2, 4]
print list(set(chain(list1, list2)))
# [1, 2, 3, 4]
A way could be using built in type set:
list(set(list1).union(list2))
You would need to store the result of the operation, if you wanted to extend list1 then you can assign it to list1:
list1=list(set(list1).union(list2))
Note: Keep in mind that this approach may not keep the order of the elements in the list.
Hope this helps!

Why this Python expression doesn't produce expected result?

This code snippet:
a = [3, 2, 1]
a.sort()
produces [1, 2, 3] list. Why
[3, 2, 1].sort()
doesn't produce the same result? Is there a "one-liner" to accomplish this?
You can use
sorted_array = sorted([2,3,1])
>>> [3, 2, 1].sort()
It does sort this list object but as the number of references(variables pointing) to this list are 0, so it is garbage collected.(i.e we can't access this list anymore)
Coming to your first question, list.sort() sorts a list in-place and returns None.
>>> a = [3, 2, 1]
>>> a.sort()
>>> a
[1, 2, 3]
If you want a to stay as it is, use sorted and assign the result back to some variable.
>>> a = [3, 2, 1]
>>> b = sorted(a)
>>> b
[1, 2, 3]
>>> a
[3, 2, 1]
list.sort is a method that sorts an existing list therefore returning None
sorted is a builtin function that creates a new sorted list from its input and returns it.

Categories