The list
is the most flexible container data type in Python, it represents an ordered sequence of elements.
Some features of lists are outlined below:
- Lists can contain any type of data including strings, integers, floats, dictionaries, etc
- Lists are ordered, meaning they keep track of the order of elements
- Lists are mutable, meaning they can be changed and manipulated.
- Lists can be indexed, meaning you can access individual elements in the list
- A list can contain other lists.
Create a list using square brackets
A list
is represented using square brackets in which coma-separated elements are placed inside the brackets. We can use this notation to initialize a list.
Create a list using the list() Function
The builtin list() function is a constructor that takes an iterable object(tuple, set, string, etc) as an argument and constructs a list using the elements of the iterable.
list(iterable = None)
If an iterable is not given, ths function simply creates an empty list.
Create a list using list comprehension
List comprehension is a type of syntax in which expressions are used to create a list from existing iterables. It efficiently combines the features of for
loops and list literals.
mylist = [<expression> for <item> in <iterable>]
The results of the expression
are added to the list during each iteration. The expression can be any valid single python expression.
You can check on list comprehension to see more on its syntax and usage.
Create a list using * operator
We can use the repetition operation with an asterisk(*) operator to create a new list containing a repeating sequence of elements of a given list.
[obj] * n
The n
argument is an integer specifying the number of times to repeat the original list.