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:

python
1
2
mylist = ["apple", "banana", "cherry"]
print(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:

python
1
2
thislist = ["apple", "banana", "cherry"]
print(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:

python
1
2
3
thislist = ["apple", "banana", "cherry"]
thislist[1] = "orange"  # Changing the second item
print(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:

python
1
2
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(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:

python
1
2
thislist = ["apple", "banana", "cherry"]
print(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:

python
1
2
3
4
5
6
list1 = ["apple", "banana", "cherry"]  # List of strings
list2 = [1, 5, 7, 9, 3]  # List of integers
list3 = [True, False, False]  # List of booleans

# A list with mixed data types:
mixed_list = ["abc", 34, True, 40, "male"

Checking Data Type

You can check the data type of a list using the type() function.

Example:

python
1
2
mylist = ["apple", "banana", "cherry"]
print(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:

python
1
2
thislist = list(("apple", "banana", "cherry"))  # Note the double round-brackets
print(thislist)  # Output: ['apple', 'banana', 'cherry']

Frequently Asked Questions