Python List
A python list is a collection of elements.

All the elements of a list need not be of a single type, they can also be of different types.
This means that a single list can contain a string, an integer, a float etc.

Elements of a list are also called list items.
Create list syntax
In order to create a list, enclose the elements of a list between square brackets([ and ]) separated by a comma. Example,

sample_list = [“codippa”, 2, 5.6]

Note that the list is assigned to a variable. A list can be used with this variable only.
Printing a list
A list can be directly printed using print() function. Just supply the list variable as argument to the function and it will print the contents of the list. Example,

sample_list = [“codippa”, 2, 5.6]
print(sample_list)      # prints [“codippa”, 2, 5.6]

Empty list
An empty list does not contain any elements. Many times you do not want to assign elements to a list at the time it is created since it might happen that the elements are being added to the list dynamically.

It is possible to create an empty list and elements to them later. There are two ways of creating an empty list

1. Using Empty square brackets
Create a variable and assign it empty square brackets as shown below.

mylist = []       # create empty list
type(mylist)      # prints <class 'list'>
mylist.append(1)  # add an element to list
print(mylist)     # prints [1]

 2. Using List constructor
Create a variable and assign it an object of class list. For creating an object of class list, write list followed by parenthesis as shown below.
This syntax is called the constructor of inbuilt  list class.

mylist = list()   # create object of list
type(mylist)      # prints <class 'list'>
mylist.append(1)  # add an element to list
print(mylist)     # prints [1]

Note: If you get an error as TypeError: ‘list’ object is not callable while using second method, then you might have used a variable with name list somewhere in your code before using this syntax and you have overridden python’s built-in list with your variable.

To resolve the error remove your variable from current session by using del <variable_name>

Access elements of a list
Elements of a list can be accessed using an integer enclosed between square brackets after the name of list. The integer represents the index or position of the element.
Index of first element is 0, second is 1 and so on. This index is counted from left to right.
Thus, to access 3rd element of the list from left, use

list = [“codippa”, 2, 5.6]
print(list[2])     # prints 5.6

Negative Indexing
Python list elements can also be accessed from right to left with negative indexes where the index of first element from right will be -1, second element from right will be -2 and so on as shown below.
element indexing in python list

Example,

list = [“codippa”, 2, 5.6]
print(list[-2])          # prints 2

Modifying value of list item
It is also possible to update an item of a list after list creation. Simply assign a value to the index which you want to update. Example,

list = [“codippa”, 2, 5.6]
list[0] = "the website"   # assign a new value to first item
print(list)               # prints [“the website”, 2, 5.6]

It is not necessary that the new value should be of same type as the existing value. Thus,

list[0] = 25 is also valid.

Checking the type of a list
If you want to check if a variable is of type list, then at the python prompt, use type function with the variable as argument as

list = [“codippa”, 2, 5.6]
type(list)          # prints <class ‘list’>

Append to a list
It is also possible to add or append new items to the end of an existing list using append() method. This method takes a single argument which is the value of item to be appended.

list = [“codippa”, 2, 5.6]
list.append("python")
print(list)        # prints [“codippa”, 2, 5.6, "tutorial"]

It is also possible to add new items in between a list using insert() method.
It takes two arguments:
First is the index at which the new item will be added, and
Second is the value of new item. Index is zero based.

list = [“codippa”, 2, 5.6]
list.insert(1, 'New!!')   # adds item to second position
print(list)               # prints [“codippa”, "New!!", 2, 5.6]

If you give an index which is greater than the size of the list, then the new  item will be added at the last position.
Remove element from list
It is possible to remove an item from a list using various methods. Detailed explanation of all the methods is available here.
Iterating over a list
In order to iterate or loop through a list, use the for loop with the in keyword. Example,

list = [“codippa”, 2, 5.6]
for item in list:
   print(item)   # print each item

Here item is a user defined variable which contains the value of a list element in every iteration.
Above code produces the following output

codippa
2
5.6

For more details on how to use loops in python, head over to this section.
Combine two lists
It is possible to directly combine two lists in python. This means that elements of both the lists are merged together.

For combining two lists in python, use the concatenation or plus operator between the lists to be combined.
The result is a list that contains the elements of both the lists. Example,

list_one = [1, 2, 3]
list_two = [4, 5, 6]
list_sum = list_one + list_two
print(list_sum)

This prints

[1, 2, 3, 4, 5, 6]

Remember that this method simply merges the elements of both the lists into a third list. It does not remove any duplicate elements.
Thus, if both the lists contain the same element, then it will be present in the resulting list twice.

List comprehension
List comprehension is a shorter and cleaner method of creating a list dynamically.

Suppose you want to create a list of numbers using a for loop. Below code would be required.

nums = []
for num in range(5):
    nums.append(num)
print(nums)

With list comprehension, same can be achieved as below.

nums = [num for num in range(5)]
print(nums)

Syntax of list comprehension is

list_name = [ expression for item in range(5) ]

where expression evaluates to the list element.
Number of list elements is the same as the number of times for loop executes.
List size
Size of a list is the total number of elements or items in it. To get the size of a list, use len() function passing it the list as argument as shown below.

#create list
nums = [0,1,2,3,4]
# get size
size = len(nums)
print(size) # prints 5

Check element presence
In order to check if the list contains an element or not, use in operator between the element and list as shown below.
in returns True if the element is present in the list and False if the list does not contain the element.

nums = [0,1,2,3,4]
print(-1 in nums)

if 2 in nums:
   print('Present')

This example produces following output

False
Present
0

List methods
Following are the important methods of a python list.

S. No.MethodDescription
1.append(element)Appends or adds element to the end of list.
2.clear()Remove all elements from the list.
3.copy()Creates a copy of list. Remember that the copy is a shallow copy which means if the list contains objects then they will be shared between original and copy lists.
4.count(element)Returns the number of times element occurs in the list.
5.extend(iterable)Adds the elements from the supplied iterable to the list.
An iterable may be a string or another list. Example,

nums = [0,1]
nums.extend('abc')

nums will now be [0,1,'a','b','c']

6.index(element)Returns the index or position of element in the list.
7.insert(element, index)Inserts element before index in the list.
8.pop(index)Removes and returns the element at index in the list.
IndexError is raised if the index is out of range.
9.remove(element)Removes and returns the element from the list.
ValueError is raised if the element is not present.
10.reverse()Reverses the list.
11.sort()Sorts the list.
0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.