Python Zip List Append
python
Solution
You need to actually look at what you are creating:
>>> array1 = ['1','2','3']
>>> array2 = ['3','4','5']
>>> ziplist = zip(array1,array2)
>>> ziplist
[('1', '3'), ('2', '4'), ('3', '5')]
and then
>>> newlist = ['7', '8', '9'] # for example
>>> ziplist.append(newlist)
>>> ziplist
[('1', '3'), ('2', '4'), ('3', '5'), ['7', '8', '9']]
Clearly, that is not what you want. The most straightforward way, assuming you no longer have access to `array1` and `array2`, is to flatten `ziplist` back out using `zip` again, then add `newlist`, then re-`zip`:
>>> flatlist = zip(*ziplist)
>>> flatlist
[('1', '2', '3'), ('3', '4', '5')] # almost back to array1 and array2
>>> flatlist.append(newlist)
>>> ziplist = zip(*flatlist)
>>> ziplist
[('1', '3', '7'), ('2', '4', '8'), ('3', '5', '9')]
Alternatively, as you don't need the zipped lists in the interim, keep collecting the flat lists throughout and only `zip` at the end:
flatlist = [['1','2','3'], ['3','4','5']]
for value in dictionary.itervalues():
if '-' in value:
flatlist.append(value.split('-'))
for t in zip(*flatlist):
print " ".join(map(str, t))
Note that you may not have exactly 3 items in each tuple in `ziplist`, so I have removed that assumption.
Problem
EDIT: more info added How can I 'append' a new list to already zipped list. The main reason for doing this, I need to scan through a dictionary and split any fields with a certain character and add the resulting list to the ziplist. ``` dictionary = { 'key1': 'testing' 'key2': 'testing' 'key3': '6-7-8', } list1 = ['1','2','3'] list2 = ['3','4','5'] ziplist = zip(list1,list2) for key, value in dictionary.iteritems(): if '-' in value: newlist = value.split('-') ziplist.append(newlist) for a,b,c in ziplist: print a,b,c ``` Expected output would be ``` 1 3 6 2 4 7 3 5 8 ``` Using the above code I get the following error. ``` for a,b,c in ziplist: ValueError: need more than 2 values to unpack ``` I assume the 'newlist' list is not being appended to the ziplist. Why is this not working? Thank you in advance.