A list is a data structure in python which can store sequence of values. It is like an array of other programming languages.

A list is constructed with brackets [ ] and commas (,) separating every element in the list.

l = [1, 2, 3]

A list in python has the following properties:

  • Mutable – Unlike strings lists are mutable, means the elements inside a string can be changed.
  • Ordered – Item in list is inserted in the ordered fashion.
  • Accessible through Index – Each item in a list can be accesed by its corresponding index.

Create a List

We can easily create a list using square brackets [].

#assign a list to a variable named my_list
my_list=[1,2,3]

# list can also hold different object type for example
my_list=['string',26,18.98,'t']

list() Constructor

list() in python converts the others data types into a list object.

l = list("code") # returns ['c', 'o', 'd', 'e']

Length of List

len() function will tell you how many items are present in the list

my_list=[1,2,3]
print(len(my_list)) # 3

Access list item

An item in a list can be accessed using the index inside the square brackets.

my_list = [1,2,3,4]
print(my_list[0])  # outputs 1
print(my_list[1])  # outputs 2

Note that indexing in a list starts from 0.

To grab other items except for the first item you can append colon “:” after second index value.

my_list = [1,2,3,4]
print(my_list[1:])  # outputs [2,3,4]

Negative list Indexing

Negative indexing of a list allows accessing the value in the backward fashion.

For example, l[-1] refers to the last item in the list, l[-2] refers to second last item in the list and so on.

my_list = [1,2,3,4]
print(my_list[-1])
print(my_list[-2])

output

4
3

Add an Item to List

To add a new item to the list you can use append(). Make sure to pass the value to the append method.

my_list = [1,2,3,4]
my_list.append(5) # [1,2,3,4,5]

If you do not want to use the append() method then you can use the following shortcut.

my_list = [1,2,3,4]
my_list = my_list+[5]
print(my_list) # [1,2,3,4,5]

Change an Item in List

To change item value simply assign a new value in the corresponding index of the old item.

my_list = [1,2,3,4]
my_list[2] = 9 # [1,2,9,4]

Delete an Item from List

There are two major ways to delete or remove an item from a list.

Remove item by Index

del() and pop() are the two method to delete an item by index. Just pass the index value and corresponding item from the list get removed.

The only difference is between both the methods is that if no index is passed to pop(), then it simply removes and returns the last value of the list.

Whereas del() requires the index value and it does not reuturn the value after deletion.

my_list = [1,2,3,4]
x = my_list.pop(2)

print("Removed item:",x)
print("List:",l)

output

Removed item: 3                                                                                      
List: [1, 2, 4]

Remove an Item by Value

remove() method of list object removes the first occurrence of the item from the list. Use it when you are not sure where a particular item is in the list.

my_list = ['lol', 'ok', 'btw', 'lol']
my_list.remove('lol')
print(my_list)    # output ['ok', 'btw', 'lol']

Remove all Items

Use clear() to remove all items and completely empty the list.

my_list = ['lol', 'ok', 'btw', 'lol']
my_list.clear()
print(my_list)  # output []

No need to pass anything to clear() method.

Check if item exists in a list

To check whether an item exists in a list use “in” and “not in” operator with python if statement

my_list = ['lol', 'ok', 'btw', 'lol']
if 'btw' in my_list:
    print("present")

#output "present"
my_list = ['lol', 'ok', 'btw', 'lol']
if 'hello' not in my_list:
    print("absent")

#output "absent"

Iterate through a List

To iterate through a loop you can use for loop

my_list = ['lol', 'ok', 'btw', 'lol']

for item in my_list:
    print(item)

output

lol                                                                                                  
ok                                                                                                   
btw                                                                                                  
lol 

If you need to update the items of the list then loop through the indexes of the list using range() and len() as described below.

my_list = [1,2,3,4]

for i in range(len(my_list)):
    my_list[i] = my_list[i]*my_list[i];
    
print(my_list) # [1, 4, 9, 16]

Quick Revision

#create a list 
my_list=[1,2,3,4]
print(my_list)

#access individual item from a list let say the first item
print(my_list[0])

#grab other items except for the first item
print(my_list[1:])

#adding new item in a list
my_list+['new item']
print(my_list)

#permanently add new item in a list
my_list=my_list=['permanent add']
print(my_list)

#double your list
print(my_list*2)

#append element in a list
my_list.append(5)
print(my_list)

# pop (delete) element from a list
my_list.pop(0)
print(my_list)
[1,2,3,4]

[1]

[2,3,4]

[1,2,3,4,'new item']

[1,2,3,4,'permanent add']

[1,2,3,4,1,2,3,4]

[1,2,3,4,5]

[2,3,4,5]

Basic List Methods

  • sort() – Sort the values of the list in ascending order.
  • count(x) – Count the frequency of ‘x’ in the list.
  • append(x) – Add ‘x’ to the list.
  • pop() – Remove last element from the list.
  • reverse() – Reverses the list.
  • index(x) – Returns the index of element ‘x’.
  • remove(x) – Removes first appearance of ‘x’ from the list.
  • clear() – Removes all elements from the list.

Leave a Reply

4 × 3 =