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 Custom Exceptions
Python Program to Find Numbers Divisible by Another Number
Python Tuple index()
Python Program to Get Line Count of a File
Python Program to Convert Decimal to Binary Using Recursion
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Set union()
Python isinstance()
Python issubclass()
Python memoryview()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python locals()
Python Object Oriented Programming
Python Program to Find Factorial of Number Using Recursion
Python Program to Add Two Matrices
Python Program to Swap Two Variables
Python String replace()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Create a Countdown Timer
Python chr()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python datetime
Python Program to Find the Size (Resolution) of a Image
Python Program to Get the File Name From the File Path
Python Program to Convert Two Lists Into a Dictionary
Python abs()
Python time Module
Python String isprintable()
Python Program Read a File Line by Line Into a List
Python Program to Shuffle Deck of Cards
Python Anonymous / Lambda Function
Python String rjust()