Lists in Python are versatile containers used to store multiple items within a single variable. They are one of Python’s four built-in data types for handling collections of data, alongside Tuples, Sets, and Dictionaries. Each of these types has unique features and use cases.
Creating Lists
Lists are defined using square brackets. For instance, you can create a list of books as follows:
mylist = ["1984", "Brave New World", "Fahrenheit 451"]
To view the contents of the list, use:
print(mylist)
Properties of Lists
Ordered
Lists maintain a defined order for items, which remains consistent. New elements are appended to the end of the list. While some methods may reorder items, the default behavior preserves the initial order.
Changeable
Lists are mutable, meaning you can alter, add, or remove elements after creation. This flexibility makes lists a dynamic data structure for various needs.
Allowing Duplicates
Lists can contain duplicate values since they are indexed. Each element’s position is identified by an index, starting at 0.
thislist = ["1984", "Brave New World", "Fahrenheit 451", "1984", "Fahrenheit 451"]
Printing this list will include all duplicate values:
print(thislist)
List Length
To find out how many items are in a list, use the len()
function:
thislist = ["1984", "Brave New World", "Fahrenheit 451"]
print(len(thislist))
Data Types in Lists
Lists can store items of any data type:
list1 = ["1984", "Brave New World", "Fahrenheit 451"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
Lists can also mix data types:
mixed_list = ["To Kill a Mockingbird", 34, True, 40, "Science Fiction"]
To check a list’s data type, use:
mylist = ["1984", "Brave New World", "Fahrenheit 451"]
print(type(mylist))
The list()
Constructor
You can also create lists using the list()
constructor. This approach requires double parentheses:
thislist = list(("1984", "Brave New World", "Fahrenheit 451"))
print(thislist)
Python Collections
Python offers four primary collection data types:
- List: Ordered, mutable, and allows duplicates.
- Tuple: Ordered, immutable, and allows duplicates.
- Set: Unordered, immutable*, and does not allow duplicates.
- Dictionary: Ordered** and mutable, with no duplicate keys.
*Sets are immutable in terms of item values but allow modification of the set itself by adding or removing items.
**As of Python 3.7, dictionaries maintain insertion order. Prior versions did not guarantee order.
Understanding these collection types helps in selecting the appropriate type based on data needs, impacting efficiency and data handling.