Understanding Python Lists: Creation and Basics
Learn the fundamentals of Python lists, a versatile data structure used to store multiple items in a single variable. Discover how to create lists using square brackets with a practical example and understand their role among Python’s built-in data types like Tuples, Sets, and Dictionaries.
Python Lists
Lists in Python are used to store multiple items in a single variable. They are one of the four built-in data types for storing collections, alongside Tuples, Sets, and Dictionaries, each with their unique characteristics and uses.
Creating a List
Lists are created using square brackets:
Example
thislist = ["orange", "grape", "melon"]
print(thislist)
Output
['orange', 'grape', 'melon']
List Items
List items are ordered, changeable, and allow duplicate values. They are indexed, starting from index [0] for the first item, index [1] for the second item, and so on.
Ordered
When we say that lists are ordered, it means that the items have a defined order that will not change. New items added to the list will appear at the end of the list.
Note: Some list methods can change the order, but generally, the order remains constant.
Changeable
Lists are changeable, meaning we can modify, add, and remove items after the list has been created.
Allow Duplicates
Lists allow duplicate values because they are indexed:
Example
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
Output
['apple', 'banana', 'cherry', 'apple', 'cherry']
List Length
To determine the number of items in a list, use the len()
function:
Example
thislist = ["orange", "grape", "melon"]
print(len(thislist))
Output
3
List Items - Data Types
List items can be of any data type:
Example
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
list4 = ["abc", 34, True, 40, "male"] #A list can also contain different data types:
Type of a List
From Python's perspective, lists are defined as objects with the data type 'list':
Example
mylist = ["orange", "grape", "melon"]
print(type(mylist))
Output
<class 'list'>
The list()
Constructor
You can also create a list using the list()
constructor:
Example
thislist = list(("orange", "grape", "melon")) # note the double round-brackets
print(thislist)
Output
['orange', 'grape', 'melon']
Python Collections (Arrays)
Python has four collection data types:
- List: Ordered and changeable. Allows duplicate members.
- Tuple: Ordered and unchangeable. Allows duplicate members.
- Set: Unordered, unchangeable*, and unindexed. No duplicate members.
- Dictionary: Ordered** and changeable. No duplicate members.
*Set items are unchangeable, but you can add and remove items.
**As of Python version 3.7, dictionaries maintain order. In Python 3.6 and earlier, they are unordered.
Choosing the right collection type for a particular dataset can enhance efficiency and maintain the meaning of data.