Convert List to Sequence of Variables in Python (2 Examples)
Hi! This short tutorial will show you 2 examples of how to turn a list to a sequence of variables in the Python programming language.
First, though, here is a quick overview of this tutorial:
Let’s get right into the Python code!
Create Sample List
Here, we will create the sample Python list that will be transformed into a sequence of variables. In reality, though, the list elements are simply being unpacked into variables.
In your Python IDE, run the line of code below to create the sample list.
my_list = [1, 2, 3, 4, 5] print(type(my_list)) # <class 'list'>
Example 1: Transform List to Sequence of Variables by Unpacking First Three Elements
In this first example, we will turn the list into a sequence of variables by unpacking the first three elements of the list.
my_list = [1, 2, 3, 4, 5] a, b, c = my_list[:3] print(a) print(b) print(c) # 1 # 2 # 3
In this first example, we used a slice to extract the first three elements of the list and used an iterable to assign them to variables: a, b and c.
Example 2: Transform List to Sequence of Variables by Unpacking all Elements
In this second example, we will convert the list to a sequence of variables by unpacking all elements in the list.
a, b, c, d, e = my_list print(a) print(b) print(c) print(d) print(e) # 1 # 2 # 3 # 4 # 5
In this example, we didn’t slice our list: my_list as in example 1 to assign all elements in the list to variables.
With that, we have demonstrated how to convert a list to a sequence of variables in Python. I hope you found this tutorial helpful!
Video, Further Resources & Summary
Do you need more explanations on how to convert a list to a sequence of variables in Python? Then you should look at the following YouTube video of the Statistics Globe YouTube channel.
In the video, we explain in more detail how to convert a list to a sequence of variables in Python.
The YouTube video will be added soon.
Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these ones:
- Convert List of Multiple Lists to Single List in Python (3 Examples)
- Check if List of Lists in Empty Python (2 Examples)
- Learn Python Programming
- Convert List of Boolean to Float in Python (2 Examples)
- Access Elements in Lists within Dictionary in Python (2 Examples)
This post has shown how to convert a list to a sequence of variables in Python. In case you have further questions, you may leave a comment below.
This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.
Statistics Globe Newsletter