#Python Lists
Lists are used to store multiple items in a single variable. They are one of four built-in data types in Python used to store collections of data; the other three are Tuple, Set, and Dictionary, each with different qualities and usage.
Lists are created using square brackets:
pythonmylist = ["apple", "banana", "cherry"]
#List Items
List items are ordered, changeable, and allow duplicate values. They are indexed, starting from [0].
#Key Characteristics
- Ordered: Items have a defined order that will not change. If you add new items, they are placed at the end of the list.
- Changeable: You can change, add, and remove items after the list has been created.
- Allow Duplicates: Because items are indexed, lists can have multiple items with the same value.
python# Example: Lists allow duplicate values
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
#Essential Operations
#List Length
To determine how many items a list has, use the len() function:
pythonthislist = ["apple", "banana", "cherry"]
print(len(thislist)) # Output: 3
#Data Types
List items can be of any data type, and a single list can contain mixed data types:
pythonlist1 = ["abc", 34, True, 40, "male"]
#The type() Function
From Python's perspective, lists are defined as objects with the data type 'list':
pythonmylist = ["apple", "banana", "cherry"]
print(type(mylist)) # Output: <class 'list'>
#The list() Constructor
You can also use the list() constructor to create a list. Note the use of double round brackets:
pythonthislist = list(("apple", "banana", "cherry"))
print(thislist)
#Python Collections (Arrays)
When choosing a collection type, it is useful to understand the specific properties of each:
| Collection | Ordered | Changeable | Duplicates |
|---|---|---|---|
| List | Yes | Yes | Yes |
| Tuple | Yes | No | Yes |
| Set | No | No\* | No |
| Dictionary | Yes\\ | Yes | No |
\* Note on Sets: Set items are unchangeable, but you can remove and/or add items.
\\ Note on Dictionaries: As of Python 3.7, dictionaries are ordered. In Python 3.6 and earlier, they are unordered.