Wednesday 24 January 2024

Concatenate lists using + operator

The + operator concatenate two lists into a new list, similar to how it concatenates two strings to form a new string value.

Syntax

new_list = list1 + list2

>>> even_numbers = [2, 4, 6, 8]
>>> odd_numbers = [1, 3, 5, 7]
>>> numbers = even_numbers + odd_numbers
>>> 
>>> even_numbers
[2, 4, 6, 8]
>>> 
>>> odd_numbers
[1, 3, 5, 7]
>>> 
>>> numbers
[2, 4, 6, 8, 1, 3, 5, 7]

 Above snippet demonstrates the concatenation of two lists using the + operator. Let's go through it step by step:

 

even_numbers = [2, 4, 6, 8]

This line creates a list named even_numbers containing the even numbers 2, 4, 6, and 8.

 

odd_numbers = [1, 3, 5, 7]

This line creates another list named odd_numbers containing the odd numbers 1, 3, 5, and 7.

 

numbers = even_numbers + odd_numbers

This line concatenates the even_numbers list with the odd_numbers list. The + operator, when used with lists, merges them into a single new list.

 

After executing this line, the numbers variable will hold the combined list [2, 4, 6, 8, 1, 3, 5, 7]. It first includes all elements from even_numbers followed by all elements from odd_numbers. This results in a new list that has elements of both even_numbers and odd_numbers in the order they were concatenated.

Previous                                                 Next                                                 Home

No comments:

Post a Comment