About Python List
In Python, list is a mutable sequence, typically used to store collections of items.
List is mutable, which means you can change the list elements (items) after it has been created.
List can contain items of different data types, though it is typically used to store collections of homogeneous items.
In Python, list items are placed inside square brackets '[]' and items are separated with comma (,).
Creating a list in Python
Using square brackets []:
-
Create a list of string (collection of fruit names like "Apple", "Banana", "Cherry", "Orange") separated by comma (,) and place them inside square brackets. The code will look like this:
["Apple", "Banana", "Cherry", "Orange"]
. -
Create a variable name
fruit_list
and assign the list of string to the fruit_list variable. Use print() function to print the list.
Please take a closer look at the following example:
Example of creating list using square brackets []
Output of the above example
The fruit list is: ['Apple', 'Banana', 'Cherry', 'Orange']
Using the list() constructor:
You can create a list by passing an iterable like a string, tuple, or another list to the list()
constructor.
List from string:
-
Create a string
"Python"
and pass it inside list() constructor like this -list("Python")
. It will create a list of char. -
Create a variable name
char_list
and assign the list to the char_list variable. Use print() function to print the list.
List from tuple:
-
Create a tuple
(1, 2, 3, 4)
and pass it inside list() constructor like this -list((1, 2, 3, 4))
. It will create a list of integer.
Please take a closer look at the following examples:
Example of creating list using list() constructor from string and tuple
Output of the above example
The char list is: ['P', 'y', 't', 'h', 'o', 'n'] List from Tuple: [1, 2, 3, 4]
Create an empty list:
-
Create a variable name
empty_list
and assign only the list() constructor to the empty_list variable as shown in the following example. Use print() function to print the empty list. It will print '[]'. -
You can add elements to the empty_list object using append() method. The following code
empty_list.append("Banana")
andempty_list.append("Orange")
add "Banana" and "Orange" to the empty list.
Please take a closer look at the following example:
Example of creating list using list() constructor
Output of the above example
Empty list: [] Elements added to empty list: ['Banana', 'Orange']
Using list comprehension
- You can create a list in a concisely based on existing iterables.
-
In the first example, a list is created from a
range(6)
. - In the second example, a list is created from a set.
Example of creating list using list comprehension
Output of the above example
list comprehension from range: [0, 1, 2, 3, 4, 5] list comprehension from set: [1, 2, 3, 4]