-2

I have a list of lists

ls = [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23]]

in each of the sub lists I would like to inset a name at the end e.g...

names = ['Dave', 'Bob']

ls = [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10, 'Dave'], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23, 'Bob']]

what's the most straight forward way to do that which can be scaled when the list of lists grows very large?

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65

2 Answers2

1

Generally, if you want to append an item to a list within a list, you can just loop it and append(item) to the (end of the) list.

for item in ls:
    item.append('Dave')

Since you're trying to operate on two lists at once you can use the built-in zip function.

ls = [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23]]
names = ['Dave', 'Bob']
for list_item, name in zip(ls, names):
    list_item.append(name)

This works on lists of the same length. If there is a risk that your lists have different sizes, try using the answer to this question

  • thanks. Ive edited the question, I am not trying to map 2 lists of the same length. My real life scenario as a very long list of lists to which I want to append a name to each. – DaveTheRave Apr 09 '22 at 20:58
  • @DaveTheRave If the name is the same, all you have to do is `append` to each list (I've updated the answer with this solution). Or are you working with different list sizes? – Tudor Amariei Apr 09 '22 at 21:14
-2

Try something like this:

ls = [[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23]]
new_vals = ['Dave', 'Bob']

# Create a function
# Accept existing list and new values (list) as arguments
def add_new_elems(_my_list, _new_vals):
    assert len(_my_list) == len(new_vals), 'Length of existing list and new values is not same'
    # Utilize list comprehension to append data
    [_my_list[i].append(_new_vals[i]) for i in range(len(_my_list))]
    return _my_list


print(add_new_elems(ls, new_vals))
######
[[1649534580000, 165.76, 165.86, 165.57, 165.57, 27.45, 10, 'Dave'], [1649534640000, 165.6, 165.69, 165.42, 165.46, 44.1, 23, 'Bob']]
  • 1
    You should not use list comprehensions for side effects. You allocate a list for not reason and just throw it away. – Mark Apr 09 '22 at 21:07
  • @Mark: I did not think about the side effects. Thanks, I'll read through the side effects. – Ashish Samarth Apr 09 '22 at 21:12