List#
Overview#
A list is a collection of elements (i.e., numbers, strings, etc) that are ordered and indexed. Lists are defined using square brackets []
or List()
, and individual elements are separated by commas (e.g., new_list = [1, 2, 3]).
Note
General syntax
my_list = [element1, element2, element3, ..., elementN]
my_list
: List variableelement1
,element2
,element3
, …,elementN
: The elements of the list.These elements can be of any data type and are enclosed in square brackets
[]
, and are separated by commas
Examples#
Examples
numbers = [1, 2, 3, 4, 5]
earth_elements = ["earth", "water", "land"]
my_list = [1, 2, 3, "water", "land", True]
mixed_list = [1, "earth", True, 3.14]
Access individual elements of the list using their index, starting from 0.
mixed = [1, "earth", True, 3.14]
print(mixed[0]) # 1
print(mixed[1]) # "earth"
print(mixed[1:3]) # "earth", True
1
earth
['earth', True]
Important
Lists are mutable (i.e., can be modified after creation), and you can add, remove, or modify elements of the list anytime.
Modify the values of specific elements using their index
mixed = [1, "earth", True, 3.14]
mixed[1] = 'new element replacing the old one'
print(mixed) # [1, 'new element replacing the old one',, True 3.14]
[1, 'new element replacing the old one', True, 3.14]
Perform operations on lists such as appending, inserting, and removing items
mixed = [1, "earth", True, 3.14]
mixed.append("engineering") # Add an item to the end of the list
print(mixed) # [1, "earth", True, 3.14, "engineering"]
mixed.insert(2, "newinsert") # Insert an item at a specific index
print(mixed) # [1, "earth", "newinsert", True, 3.14, "engineering"]
mixed.remove("earth") # Remove a specific item
print(mixed) # [1, "newinsert", True, 3.14, "engineering"]
[1, 'earth', True, 3.14, 'engineering']
[1, 'earth', 'newinsert', True, 3.14, 'engineering']
[1, 'newinsert', True, 3.14, 'engineering']