Python Lists

Python lists are containers to store a set of values of any data type. In lists, values are in a comma-separated way between square brackets. Values can be of any data type such as either containing a single data type like string, int only, or mixed types like string, int, boolean, etc. together.

Lists containing the same data types

python-lists-same-data-types

Lists containing different data types

python-lists-different-data-types

Here, in the above example, list2 contains different data types like numbers(int, float), string, boolean, and lists. You can also check the data type of values inside list2 as:

list2 = ['PythonSansar', 2022, 2.34, True, [1, 3, 5]]

# loop through list2
for value in list2:
   print(f'Value: {value} data type -> {type(value)}')

Output:

Value: PythonSansar data type -> <class 'str'>
Value: 2022 data type -> <class 'int'>
Value: 2.34 data type -> <class 'float'>
Value: True data type -> <class 'bool'>
Value: [1, 3, 5] data type -> <class 'list'>

Creating List

Python list can be created by two methods:

1. By list constructor: list( )

>>> list3 = list()
>>> type(list3)
<class 'list'>
>>> list3 = list(("List", "Set", "Dictionary", "Tuple"))
>>> list3
['List', 'Set', 'Dictionary', 'Tuple']
>>>

Note: Make sure to place list items inside parenthesis inside list constructor.

2. By simply placing square brackets: [ ]

>>> list4 = []
>>> type(list4)
<class 'list'>
>>> list4 = ["Learn", "Python", "Lists"]
>>> list4
['Learn', 'Python', 'Lists']
>>>

Indexing List

Python list can be indexed just like a string starting with the first index value 0 and so on. 

In string, each character is indexed with a certain value starting from 0, and we can access those characters by passing its index value.

Let’s take a simple example with “PythonSansar” as a string.

>>> string1 = "PythonSansar"
>>> #get first character
>>> string1[0]
'P'
>>> #get last character
>>> string1[-1]
'r'
>>>

Let’s try the same with the list items as:

list5 = [“Mark”, “Elon”, “Jeff”, “Bill”]

>>> list5 = ["Mark", "Elon", "Jeff", "Bill"]
>>> list5[0]
'Mark'
>>> list5[1]
'Elon'
>>> list5[3]
'Bill'
>>> list5[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>

Note: Since we have four items on the list5 we can access items from index range 0 to 4. Any other value pass different from index ranges results in “IndexError”.

Python Built-in functions on list

List support different python built-in functions like len( ), max( ), min( ), sum( ), and many others.

list6 = [10, 20, 30, 40, 50]

Length of the list: len( )

>>> len(list6)
5

Maximum item on the list: max( )

>>> max(list6)
50

Minimum item on the list: min()

>>> min(list6)
10

Sum of the list items: sum( )

>>> sum(list6)
150
>>>

Check out more on list: Python List Methods

Leave a Comment