Welcome to this tutorial on How to Create a Python List, which is used to store multiple Elements into a single Python Variable.
Python Lists are Ordered, Mutable and allow for Duplicates. The easiest way to recognize a Python List, is by its usage of Square Brackets [ ] which no other collection Data Type uses.
Lists are one of 4 built-in data types in Python, that are used to store collections of data. The other 3 Python Iterables (Collection Data Types) are Tuples, Sets, and Dictionaries, each with their own different qualities and usages.
NOTE: This tutorial requires that Python is already installed, as well as an IDE (Integrated Development Environment), such as PyCharm. It’s also recommended that you have a basic understanding of How to Use Python if this is your first time learning Python, as well as Python Variables and Data Types.
With that said, let’s get started with this free Python Lists tutorial.
How to Create a List in Python
A Python List is created using Square Brackets [ ], in which its Elements are stored. A List is assigned to a Variable name as follows:
List_Variable_Name = [List_Element0, List_Element1, List_Element2, List_Element3]
Python List Example:
Here is a Python List that contains three fruits as its Elements, in the form of Strings, assigned as a Variable named “fruit_list”:
fruit_list = ["apple", "orange", "banana"]
print(fruit_list)
#>> ['apple', 'orange', 'banana']
We then print out the “fruit_list” Variable by using the “print(fruit_list)” statement. Python outputs [‘apple’, ‘orange’, ‘banana’] which is our List of fruits.
Square Brackets [ ] are Required when creating a Python List
If the Square Brackets [ ] are not used when trying to create a Python List, then it will default to a Python Tuple instead:
fruit_list = "apple", "orange", "banana"
print(fruit_list)
#>> ('apple', 'orange', 'banana') # A Tuple is created instead of the intended List
As we can see, the Square Brackets [ ] are a requirement when creating a Python List, as it defaults to a Tuple when not used.
Python Lists work with only a Single Element
A Python List can be created with only one Element, which unlike a Tuple, requires 2 more more Elements.
For example, if there is only one Element in the List, such as “apple”, it remains a List. We can test this using the type() Function:
fruit_list = ["apple"]
print(fruit_list)
print(type(fruit_list)) # Calling the “fruit_list” Variable inside of the type() Function
#>> ['apple']
#>> <class 'list'> # Confirmation that this is in fact a List
The “apple” is the only Element in the List, yet Python still accepts it as a legitimate List, which we can see when using the type() Function. This is the opposite of a Tuple, which would output “apple” as a String.
Python Lists don’t require any Elements
Python Lists can even be completely empty, requiring no Elements at all, and will still be seen as a List Data Type by Python:
fruit_list = []
print(fruit_list)
print(type(fruit_list)) # Calling the “fruit_list” Variable inside of the type() Function
#>> []
#>> <class 'list'> # Confirmation that this is in fact a List
Again, we see that this still remains a List, even with no Elements added to it.
Data Type Elements that a Python List can contain
Python Lists can contain any of the following Data Types as Elements, both individually or mixed within a single List:
- Integers (int) – Whole numbers such as: 1, 14, 576.
- Floating Point (float) – Decimal values such as: 1.24, 5.6 and Fractional Values such as 1/2, 9/6.
- Strings (str) – Sequence of Characters such as: “I love Python”, “this course is great”, “year 3000”.
- Booleans (bool) – Logical values representing: TRUE or FALSE.
For example, we are able to create the following mixed Data Type list:
mixed_list = [14, 365.34, "welcome", True] #int, float, string, bool
print(mixed_list)
#>> [14, 365.34, "welcome", True]
All four Data Types, including the int, float, string and bool were successfully output within the List.
Python Iterables that can be stored within a List
Python Lists aren’t limited to only storing single Data Types either. Lists are able to store other Python Iterables (Collection Data Types) within them, including Tuples, Sets, Dictionaries and even a List within a List.
Here is an example of a Python List with a Tuple, Set, Dictionary and a List stored as its Elements:
mixed_iterable_list = [("apple", "orange"), {"apple", "orange"}, {"a": 1, "b": 2}, ["apple", "orange"]] #tuple, set, dictionary, list
print(mixed_iterable_list)
#>> [('apple', 'orange'), {'apple', 'orange'}, {'a': 1, 'b': 2}, ['apple', 'orange']]
Using the Print Statement to output the results, we can see that Python successfully accepted the other Iterables as ELements within the List.
How to Check for a Python List using the type() Function
If you are unsure if a variable or output is in fact a List, you can easily check this using the type() Function:
fruit_list = ["apple", "orange", "banana"]
print(fruit_list)
print(type(fruit_list)) # type() Function within Print Statement
#>> ['apple', 'orange', 'banana']
#>> <class 'list'> # Confirmation that this is a List
Python outputs <class ‘list’>, which confirm to us that the Variable is indeed a List.
How to Check the Length of a Python List using len() Function
The length of a Python List can be defined using the len() Function:
fruit_list = ["apple", "orange", "banana"]
print(len(fruit_list))
#>> 3
This outputs the number 3 (int), which tells us how many Elements we have in our Python List.
Python Lists are Ordered, Mutable & Allow Duplicates
A Python List is Ordered, Mutable, and allows for Duplicate Elements. Lists are similar to Tuples, except that a Tuple cannot be changed after its creation, while a List can.
Python Lists are Ordered
Python Lists are Ordered and thus the Elements with a List have a defined order.
Being Ordered means that no matter how many times a Python List is output by Python (such as using a Print Statement), the order of the Elements in the List will not change:
# FIRST RUN
fruit_list = ["apple", "orange", "banana"]
print(fruit_list)
#>> ['apple', 'banana', 'orange'] #Same output order
# SECOND RUN
fruit_list = ["apple", "orange", "banana"]
print(fruit_list)
#>> ['apple', 'banana', 'orange'] #Same output order
# THIRD RUN
fruit_list = ["apple", "orange", "banana"]
print(fruit_list)
#>> ['apple', 'banana', 'orange'] #Same output order
Each output run will keep the Elements of the List in the exact same defined order of the original List, unlike Sets (set) which will randomize the order of the Elements every time.
Python Lists are Mutable
Python Lists are also Mutable, meaning that we can change, add and remove Elements in a List after it has been created, using the available List Methods:
Python List Methods
- append() : Adds an element at the end of the list
- clear() : Removes all Elements of a List
- copy() : Returns a Copy of a List
- count() : Returns the number of Elements with a specified Value
- extend() : Adds the Element of List or any other Iterable to the end of the List
- index() : Returns the Index of the FIRST element with the specified Value
- insert() : Adds an Element at a specified position
- pop() : Removes the Element at a specified Position (default end position)
- remove() : Removes the Element with a specified Value
- reverse() : Reverses a List
- sort() : Sorts a List
Python Lists Allow Duplicates
Python Lists also allow for duplicate Elements:
fruit_list = ["apple", "orange", "banana", "apple"]
print(fruit_list)
#>> ['apple', 'orange', 'banana', "apple]
Here we can see that we have two copies of the “apple” Element.
Python Lists Conclusion
I hope you enjoyed this tutorial on how to create a Python List. This should give you the starting knowledge you need to easily create Lists in Python for your code or project.
Python List Summary
Here is a summary of what we learnt when creating a Python List:
- Python Lists use and require Square Brackets [ ].
- Python Lists can be created using a single Element.
- Python Lists can be empty with no Elements at all.
- Python Lists can contain Integer (int), Floating Point (float), Strings (str) and Booleans (bool) Data Types as their Elements.
- Python Lists can contain other Python Iterables, such as Tuples, Sets, Dictionaries and even other Lists as their Elements.
- The type() Function can be used to check if a Variable is a List.
- The len() Function can be used to check the Length of a List.
- Python Lists are Ordered, meaning that the Elements will always have a defined order that will not change.
- Python Lists are Mutable, meaning that Elements can be changed, added, removed, sorted, reversed using Methods.
- Python Lists allow for Duplicate Elements, meaning that it is possible to have two or more of the same Elements in a List.
Remember, that when choosing a the Python Iterables (List, Tuple, Set or Dictionary) for your code, it is very important to choose the correct one for the required use case, as each of the Python Iterables has it own qualities and properties, which have a direct influence on both performance and security of your code.
Full Python Beginners Course
This tutorial is just a small sample of the my Full Python Beginners Course. The entire course is recorded and available in High Definition video, allowing you to easily learn Python as you watch and follow along. If you have been wanting to start learning Python, but haven’t been sure where to start, then this is the course for you, so don’t to miss out!
Share the love
If you enjoyed this tutorial content and would like others to benefit from it as well, make sure to share it on your favorite Social Media platform, using the share buttons below.
Subscribe for News & Discount Offers
Subscribe right now to gain instant access to the latest news and tutorials while also being the first to know about, exclusive offers and discounts!