Table of Contents
In this example, you will learn to concatenate two lists in Python.
To understand this example, you should have the knowledge of the following Python programming topics:
- Python List
- Python List extend()
1. Example 1: Using + operator
list_1 = [1, 'a'] list_2 = [3, 4, 5] list_joined = list_1 + list_2 print(list_joined)
Output
[1, 'a', 3, 4, 5]
In this example, +
operator is used to concatenate two lists.
2. Example 2: Using iterable unpacking operator *
list_1 = [1, 'a'] list_2 = range(2, 4) list_joined = [*list_1, *list_2] print(list_joined)
Output
[1, 'a', 2, 3]
*
operator allows unpacking inside the list or tuple.
3. Example 3: With unique values
list_1 = [1, 'a'] list_2 = [1, 2, 3] list_joined = list(set(list_1 + list_2)) print(list_joined)
Output
[1, 2, 3, 'a']
If you want the unique items from a concatenated list, you can use list()
and set()
. set()
selects the unique values and list()
converts the set into list.
4. Example 4: Using extend()
list_1 = [1, 'a'] list_2 = [1, 2, 3] list_2.extend(list_1) print(list_2)
Output
[1, 2, 3, 1, 'a']
Using extend()
, you can concatenate a list to another list as shown in example above.
Related posts:
Python Program to Check if a Number is Odd or Even
Python list()
Python frozenset()
Python enumerate()
Python String splitlines()
Python Namespace and Scope
Python Program to Copy a File
Python Program to Count the Occurrence of an Item in a List
Python String casefold()
Python Program to Print all Prime Numbers in an Interval
Python Set issuperset()
Python Program to Find Sum of Natural Numbers Using Recursion
Python *args and **kwargs
Python Set issubset()
Python String zfill()
Python String endswith()
Python Program to Get the Full Path of the Current Working Directory
Python String title()
Python Exception Handling Using try, except and finally statement
Python String islower()
Python Global Keyword
Python String index()
Python List Comprehension
Python Program to Create Pyramid Patterns
Python String format_map()
Python complex()
Python Program to Count the Number of Digits Present In a Number
Python Shallow Copy and Deep Copy
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Closures
Python slice()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper