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 an empty list
empty_list = []
print(empty_list)
#create a list of integers
integer_list = [1, 2, 3, 4]
print(integer_list)
#create a list of strings
string_list = ['Python', 'Java', 'C++']
print(string_list)
#create a list of lists
my_list = [[1, 2], [3, 4], [5, 6]]
print(my_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 an empty list
empty_list = list()
print(empty_list)
#create a list from a tuple
my_tuple = (1, 2, 3, 4)
integer_list = list(my_tuple)
print(integer_list)
#create a list from a string
my_string = "ABCD"
my_list = list(my_string)
print(my_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.
#create a list of zeroes
list1 = [0 for i in range(10)]
print(list1)
#create a list with the elements of the iterable
list2 = [i for i in (1, 2, 3, 4, 5)]
print(list2)
#create a list of odd numbers
list3 = [n for n in range(20) if n%2]
print(list3)
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.
#creat a list of zeroes
list1 = [0] * 10
print(list1)
#create a list of repeating tuples
list2 = [(1, 2)] * 5
print(list2)