Take the content of a list and append it to another list
You probably want
list2.extend(list1)
instead of
list2.append(list1)
Here's the difference:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = [7, 8, 9]
>>> b.append(a)
>>> b
[4, 5, 6, [1, 2, 3]]
>>> c.extend(a)
>>> c
[7, 8, 9, 1, 2, 3]
Since list.extend()
accepts an arbitrary iterable, you can also replace
for line in mylog:
list1.append(line)
by
list1.extend(mylog)
How to append a list to another list in a python for loop when each element of the existing list is being changed inside the for loop?
When you append r1
twice to r2
it essentially makes r2
a list of [r1, r1]
not the contents of r1
when it was appended, so when r1
is changed before the second append, the first element in r2
which is a reference to r1
is also changed.
One solution is to not use r1 at all and just append the contents directly:
r2 = []
r_1 = {'G':32,'H':3}
for i in r_1:
r2.append([i, i+"I"])
print(r2)
A second solution is to append a copy of r1 to avoid the two elements having the same reference:
r2 = []
r_1 = {'G':32,'H':3}
r1 = [None, None]
for i in r_1:
r1[0] = i
r1[1] = i + "I"
r2.append(r1.copy())
print(r2)
How to append all elements of one list to another one?
You could use addition:
>>> a=[5, 'str1']
>>> b=[8, 'str2'] + a
>>> b
[8, 'str2', 5, 'str1']
How to Append a List Key Value using Another List
JSON you posted is invalid so I fixed it little bit. Following code should work:
list_1 = [
{
"name": "John",
"measurement": "5.11"
},
{
"name": "Kate",
"measurement": "5.6"
}
]
list_2 = [
{
"name": "John",
"characteristics": {
"height": "6.0",
"age": 30
}
},
{
"name": "Mike",
"characteristics": {
"height": "5.10",
"age": 25
}
}
]
result = []
for list_1_item in list_1:
single_obj = {}
for list_2_item in list_2:
if list_2_item['name'] == list_1_item['name']:
single_obj['name'] = list_1_item['name']
single_obj['characteristics'] = list_2_item['characteristics']
result.append(single_obj)
print(result)
This gives us following result:
[{'name': 'John', 'characteristics': {'height': '6.0', 'age': 30}}]
Python: Append a list to another list and Clear the first list
Passing a list
to a method like append
is just passing a reference to the same list
referred to by list1
, so that's what gets appended to list2
. They're still the same list
, just referenced from two different places.
If you want to cut the tie between them, either:
- Insert a copy of
list1
, notlist1
itself, e.g.list2.append(list1[:])
, or - Replace
list1
with a freshlist
afterappend
ing instead of clearing in place, changingdel list1[:]
tolist1 = []
Note: It's a little unclear, but if you want the contents of list1
to be added to list2
(so list2
should become [1, 2, 3]
not [[1, 2, 3]]
with the values in the nested list
), you'd want to call list2.extend(list1)
, not append
, and in that case, no shallow copies are needed; the values from list1
at that time would be individually append
ed, and no further tie would exist between list1
and list2
(since the values are immutable int
s; if they were mutable, say, nested list
s, dict
s, etc., you'd need to copy them to completely sever the tie, e.g. with copy.deepcopy
for complex nested structure).
How do I append to list only after a certain value in another python list?
Use the list.index
method to return the index i
where the value
appears in the old_list
. Then slice old_list
from index i+1
up to its end:
old_list = ['apple', 'pear','orange', 'banana', 'grape']
value = 'orange'
i = old_list.index(value)
new_list = old_list[i+1:]
Cannot append a list to another list when both lists are passed into function as parameters
Your problem is actually not that res.append(cur)
"doesn't work" - it of course works as expected -, but with how it works.
Python's "variables" are not symbolic names for memory locations, they are just name=>object pairs, and the same object can be referenced by many names at once. If you mutate an object thru one of it's name, you'll see the effect thru all the other names it's bound to, because all those names point to the same object:
>>> a = list("abc")
>>> a
['a', 'b', 'c']
>>> b = a
>>> c = b
>>> a is b
True
>>> a is c
True
>>> b.append("d")
>>> c
['a', 'b', 'c', 'd']
>>> a
['a', 'b', 'c', 'd']
>>> b
['a', 'b', 'c', 'd']
>>> c.pop()
'd'
>>> a
['a', 'b', 'c']
>>> b
['a', 'b', 'c']
>>> c
['a', 'b', 'c']
>>>
And this works the same for any attribute, collection etc, including of course lists of lists:
>>> lst = [a]
>>> lst[0]
['a', 'b', 'c']
>>> lst[0]
['a', 'b', 'c']
>>> c.append(42)
>>> lst
[['a', 'b', 'c', 42]]
Also, Python never implicitely copies anything - when you pass an object to a function, the function gets the object, not a copy of it:
>>> def foo(lst):
... print("in foo, lst = {} (id : {})".format(lst, id(lst)))
... lst.append([42])
...
>>> id(a)
140278039812000
>>> foo(a)
in foo, lst = ['a', 'b', 'c', 42] (id : 140278039812000)
>>> a
['a', 'b', 'c', 42, [42]]
So in your helper
function, you have this:
if index == len(set_list):
if cur not in res:
res.append(cur) # -> if I change this to res.append(cur[:]) this works
return
helper(set_list, index + 1, res, cur)
cur.append(set_list[index]) # HERE
helper(set_list, index + 1, res, cur)
cur.pop() # AND HERE !!!!
Notice the cur.append(xxx)
and cur.pop()
calls ? Guess what ? Yes, they mutate the cur
list. The one you appended to res
. Which is why you end up with an empty result. It's rather obvious if you trace code execution:
def helper(set_list, index, res, cur):
print("helper with index %s, res %s and cur %s" % (index, res, cur))
if index == len(set_list):
if cur not in res:
print("append %s to %s" % (cur, res))
res.append(cur) # -> if I change this to res.append(cur[:]) this works
return
print("first recursive call")
helper(set_list, index + 1, res, cur)
print("now res is %s and cur is %s" % (res, cur))
print("appending to cur")
cur.append(set_list[index])
print("now cur is %s" % cur)
print("second recursive call")
helper(set_list, index + 1, res, cur)
print("now res is %s and cur is %s" % (res, cur))
print("poping from cur")
cur.pop()
print("now res is %s and cur is %s" % (res, cur))
which produces:
helper with index 0, res [] and cur []
first recursive call
helper with index 1, res [] and cur []
first recursive call
helper with index 2, res [] and cur []
first recursive call
helper with index 3, res [] and cur []
append [] to []
now res is [[]] and cur is []
appending to cur
now cur is [2]
second recursive call
helper with index 3, res [[2]] and cur [2]
now res is [[2]] and cur is [2]
poping from cur
now res is [[]] and cur is []
now res is [[]] and cur is []
appending to cur
now cur is [2]
second recursive call
helper with index 2, res [[2]] and cur [2]
first recursive call
helper with index 3, res [[2]] and cur [2]
now res is [[2]] and cur is [2]
appending to cur
now cur is [2, 2]
second recursive call
helper with index 3, res [[2, 2]] and cur [2, 2]
now res is [[2, 2]] and cur is [2, 2]
poping from cur
now res is [[2]] and cur is [2]
now res is [[2]] and cur is [2]
poping from cur
now res is [[]] and cur is []
now res is [[]] and cur is []
appending to cur
now cur is [1]
second recursive call
helper with index 1, res [[1]] and cur [1]
first recursive call
helper with index 2, res [[1]] and cur [1]
first recursive call
helper with index 3, res [[1]] and cur [1]
now res is [[1]] and cur is [1]
appending to cur
now cur is [1, 2]
second recursive call
helper with index 3, res [[1, 2]] and cur [1, 2]
now res is [[1, 2]] and cur is [1, 2]
poping from cur
now res is [[1]] and cur is [1]
now res is [[1]] and cur is [1]
appending to cur
now cur is [1, 2]
second recursive call
helper with index 2, res [[1, 2]] and cur [1, 2]
first recursive call
helper with index 3, res [[1, 2]] and cur [1, 2]
now res is [[1, 2]] and cur is [1, 2]
appending to cur
now cur is [1, 2, 2]
second recursive call
helper with index 3, res [[1, 2, 2]] and cur [1, 2, 2]
now res is [[1, 2, 2]] and cur is [1, 2, 2]
poping from cur
now res is [[1, 2]] and cur is [1, 2]
now res is [[1, 2]] and cur is [1, 2]
poping from cur
now res is [[1]] and cur is [1]
now res is [[1]] and cur is [1]
poping from cur
now res is [[]] and cur is []
[]
And which is why appending a shallow copy of res
instead solves the issue - it's a different object, so it's not affected by the cur.append()
and cur.pop()
calls.
FWIW, there's an exellent articles about this whole topic, which you certainly want to read.
Related Topics
Hiding a Password in a Python Script (Insecure Obfuscation Only)
Global Variable from a Different File Python
Subprocess.Popen() Error (No Such File or Directory) When Calling Command with Arguments as a String
How to Use Pil to Make All White Pixels Transparent
How to Set the Absolute Position of Figure Windows with Matplotlib
Inverse Distance Weighted (Idw) Interpolation with Python
Import Error: No Module Named Numpy
Interpolate Nan Values in a Numpy Array
How to Use Groupby to Concatenate Strings in Python Pandas
How to Prevent Python's Urllib(2) from Following a Redirect
Python Datetime Object Show Wrong Timezone Offset
How Does a Python for Loop with Iterable Work
Inheritance of Private and Protected Methods in Python