0
my_list = ['a','b','c']

new_item = 'd'
newest_item = 'e'

How can i get?

result = ['a','b','c','d','e']

My attempt was:

result = [x for x in my_list,new_item,newest_item]

4 Answers 4

3
>> result = my_list + [new_item, newest_item]
>> result
['a', 'b', 'c', 'd', 'e']

The + operator can be used to concatenate two lists. Note that this creates a new list result and thus preserves the original value of my_list.

Sign up to request clarification or add additional context in comments.

Comments

2

Along with @mdml's solution, you can also simply use append

>>> my_list = ['a','b','c']
>>> my_list.append('d')
>>> my_list
['a', 'b', 'c', 'd']
>>> my_list.append('e')
>>> my_list
['a', 'b', 'c', 'd', 'e']

1 Comment

Or .extend(('d', 'e')).
2

If you don't mind altering your initial list (and avoid a copy):

>>> foo = [1,2,3,4]
>>> foo.extend([5,6])
>>> foo
[1, 2, 3, 4, 5, 6]

Comments

1

You can use so many ways to achieve this result.

First of, you can append items to your list:

my_list = ['a','b','c']
my_list.append('d') -> ['a','b','c','d']
my_list.append('e') -> ['a','b','c','d', 'e']

It is handy if you need to add items in cycle.

If you have few items and you want to add all of then to list:

my_list = ['a','b','c']
my_list.extend(['d', 'e']) -> ['a','b','c','d', 'e']

Or

my_list += ['d', 'e']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.