Python List

Table of Contents

What is Python list ?

Python lists are positionally (by index) ordered collections of arbitrarily typed objects (Items can be any type).
Python lists have no fixed size.
Lists are mutable type that means they can be changed after assigned.

 

How to create List ?

Python lists can be created using square brackets [] or list() built-in function
Example 1 :

mylist = ["pythoneasy", 2016, "english"]
print(type(mylist))
<class 'list'>


We can pass an iterable (collection data type like tuple or dictionary) to list() function to create a list.
Example 2 :

tuple1 = ("pythoneasy", 2016, "english")
mylist = list(tuple1)
print(mylist)
['pythoneasy', 2016, 'english']

 

Accessing list values or objects

As list is a sequence data type, the items or objects are stored in the memory in the sequence with index starting from 0 (as shown in the below image)

list

so each element is referred to a index.
In the above example "pythoneasy" is linked to positional index 0 and 2016 to 1 and "english" to 2.
We can access these with reference mylist[0], mylist[1] and mylist[2]. This process is also known as indexing.

mylist = ["pythoneasy", 2016, "english"]
print(mylist[0]) # prints "pythoneasy"
print(mylist[1]) # prints 2016
print(mylist[2]) # prints "english"
pythoneasy
2016
english

 

Changing list values

Using the indexes we can also change the values/objects inside the list

mylist = ["pythoneasy", 2016, "english"]
mylist[1] = 2018            # Changes the second object
print(mylist)
mylist[0] = "python.org"    # Changes the first object
mylist[2] = "spanish"       # Changes the third object
print(mylist)
['pythoneasy', 2018, 'english']
['python.org', 2018, 'spanish']

 

While using index like above you need to be careful about the number of index.
As we have 3 objects/items here the maximum index will be 2 .i.e. length of the list - 1
Trying to index a value more than this will cause an IndexError
Example:

mylist = ["pythoneasy", 2016, "english"]
mylist[4] = 2018 # index more than maximum index
Traceback (most recent call last): File "D:/pythoneasy/list_example.py", line 2, in <module> mylist[4] = 2018 IndexError: list assignment index out of range

 

Length of a list

The built-in function len() helps to determine the length of a list

mylist = ["pythoneasy", 2016, "english"]
print(len(mylist))
3


The last index of index can be calculated as len(mylist) -1

mylist = ["pythoneasy", 2016, "english"]
print(mylist[len(mylist) - 1])
english


so len(mylist) - 1] provides 2 and mylist[2] results in "english"

 

Negative index

Python also supports negative index.
When we create a list, the negative index will be created from right to left starting from -1 (as shown in the below image).

list

mylist = ["pythoneasy", 2016, "english"]

In the above example mylist[-1] provides the last value always which is "english"
And the value of mylist[-3] is same as mylist[0] and mylist[-2] as mylist[1]

print(mylist[-1])
english

 

Slicing

We can also extract a range of a items from a list using indexes know as slicing.
The syntax is

variable_name[I:J] # Gives everything in variable_name from I to J, but inot including J

Example:

mylist = ["pythoneasy", 2016, "english", 2017, 2018]
print(mylist[1:4])
[2016, 'english', 2017]



So it extracts the a list from offset/index 1 to 3 (Not including 4)
Slicing also can be done using built in function slice()
Example:

mylist = ["pythoneasy", 2016, "english", 2017, 2018]
print(mylist[slice(1, 4)])
[2016, 'english', 2017]

slice(1, 4) is same as 1:4 , when provided to list, it gives a list of two element on index 1 to 3

 

List Comprehension

List comprehension provide a concise way to create lists.
Using list comprehension expression we can create a new list using another list.
Syntax :

[ output_expression for(set of values to iterate) if(conditional filtering) ]

Examples

Let us create a list containing only even numbers from another iterable using for loop.

Example 1:

tuple_1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
list_1 = list()
for element in tuple_1:
    if element % 2 == 0:
        list_1.append(element)
print(list_1)
[2, 4, 6, 8]

In the above program, list_1 is created from tuple_1 using for loop.
The above program can be done using list comprehension expression as follows

Example 2:

tuple_1 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
list_1 = [element for element in tuple_1 if element % 2 == 0] # in a single line
print(list_1)

In the above program we converted the whole for loop block to a single line using list comprehension expression to create list_1

For loop works as

for (set of values to iterate):
  if (conditional filtering):
    output_expression

The above for loop can be written using List comprehension as

[ output_expression for(set of values to iterate) if(conditional filtering) ]

Note: List comprehension mechanism is faster than for loops.

 

Python List Methods

Find list methods and usage herehttps://www.pythoneasy.com/python-programming-tutorial/python-list-methods

Click any Link
to navigate to certain page easily
Write a line to us
Your Email
Title
Description