list of the lists - append after search

Peter Otten __peter__ at web.de
Thu Mar 2 11:26:56 EST 2017


Andrew Zyman wrote:

> Hello,
>  please advise.
> 
>  I'd like search and append the internal list in the list-of-the-lists.
> 
> Example:
>  ll =[ [a,1], [b,2], [c,3], [blah, 1000] ]
> 
>  i want to search for the internal [] based on the string field and, if
>  matches, append that list with a value.
> 
>   if internal_list[0] == 'blah':
>       ll[ internal_list].append = [ 'new value']
> 
> End result:
>  ll =[ [a,1], [b,2], [c,3], [blah, 1000, 'new value'] ]

>>> outer = [["a", 1], ["b", 2], ["c", 3], ["blah", 1000]]
>>> for inner in outer:
...     if inner[0] == "blah":
...         inner.append("new value")
... 
>>> outer
[['a', 1], ['b', 2], ['c', 3], ['blah', 1000, 'new value']]


While this is what you are asking for it will get slower as the list grows. 
A better solution uses a dictionary:

>>> outer = [["a", 1], ["b", 2], ["c", 3], ["blah", 1000]]
>>> lookup = {inner[0]: inner[1:] for inner in outer}
>>> lookup
{'a': [1], 'blah': [1000], 'b': [2], 'c': [3]}
>>> lookup["blah"].append("whatever")
>>> lookup
{'a': [1], 'blah': [1000, 'whatever'], 'b': [2], 'c': [3]}





More information about the Python-list mailing list