List in Python
Python Lists
In Python, lists are versatile data structures used to store multiple items in a single variable. They are one of the four built-in data types for storing collections of data, alongside tuples, sets, and dictionaries. Each of these types has distinct qualities and usage scenarios.
1. Creating a List
Lists are created using square brackets []
, and can contain any type of data, including strings, integers, and even other lists.
Example:
1mylist = ["apple", "banana", "cherry"]
2print(mylist)
2. Characteristics of Lists
2.1. Ordered
Lists maintain a defined order for their elements. This means that when you add new items to a list, they will be placed at the end, preserving the sequence.
Example:
1thislist = ["apple", "banana", "cherry"]
2print(thislist) # Output: ['apple', 'banana', 'cherry']
2.2. Changeable
Lists are mutable, which means you can modify them after creation. You can change existing items, add new items, or remove items.
Example:
1thislist = ["apple", "banana", "cherry"]
2thislist[1] = "orange" # Changing the second item
3print(thislist) # Output: ['apple', 'orange', 'cherry']
2.3. Allow Duplicates
Lists can contain multiple items with the same value. This feature is useful for storing duplicate entries.
Example:
1thislist = ["apple", "banana", "cherry", "apple", "cherry"]
2print(thislist) # Output: ['apple', 'banana', 'cherry', 'apple', 'cherry']
3. List Length
You can determine the number of items in a list using the len()
function.
Example:
1thislist = ["apple", "banana", "cherry"]
2print(len(thislist)) # Output: 3
4. List Items - Data Types
List items can be of any data type. You can create lists containing strings, integers, booleans, or even other lists.
Example:
1list1 = ["apple", "banana", "cherry"] # List of strings
2list2 = [1, 5, 7, 9, 3] # List of integers
3list3 = [True, False, False] # List of booleans
4
5# A list with mixed data types:
6mixed_list = ["abc", 34, True, 40, "male"
Checking Data Type
You can check the data type of a list using the type()
function.
Example:
1mylist = ["apple", "banana", "cherry"]
2print(type(mylist)) # Output: <class 'list'>
5. The List() Constructor
In addition to using square brackets, you can also create a list using the list()
constructor.
Example:
1thislist = list(("apple", "banana", "cherry")) # Note the double round-brackets
2print(thislist) # Output: ['apple', 'banana', 'cherry']