Codementor Events

Complete guide about Python Lists

Published Dec 26, 2018Last updated May 02, 2022
Complete guide about Python Lists

Introduction

Lists is an ordered collection of items
Lists are the simplest data structures in python
Lists are Mutable (or) changable
Each element or value that is inside a List is called an item

Lists

Lists are great to use when you want to work with many related values. They enable you to keep data together.
The list type is a container that holds a number of other objects in a given order.
Creating a list as simple as by placing all the elements inside a square brackets[] separated by comma(,)

list = [a,b,'hi',3,5]

List Index

We can access the items in a list using index. The index starts from 0.

 a = ["hi",2,78,"hello"]
 print(a[0]) ->gives "hi"
 print(a[1]) ->gives 2

python allows negative indexing, the index -1 refers to the last item in a list.

a = ["hi",2,78,"hello"]
print(a[-1]) ->gives "hello"
print(a[-2]) ->gives 78

List Slicing

If we want to access a range of items in a list we are using slicing.
list.png

list[start:end] -> items start through end-1
list[start:]    -> items start through the rest of the array
list[:end]      -> items from the beginning through end-1
list[:]         -> This will give the whole list
list[start:end:step] -> start through not past end, by step
list[-1]    -> last item in the list
list[-2:]   -> last two items in the list
list[:-2]   -> everything except the last two items in the list
list[::-1]  -> reverse the items 
list = ['i','l','o','v','e','p','y','t','h','o','n']
print(list[2:5])
**Output: ['o', 'v', 'e']**

print(list[:-5])
**Output: ['i', 'l', 'o', 'v', 'e', 'p']**

print(list[:])
**Output: ['i', 'l', 'o', 'v', 'e', 'p', 'y', 't', 'h', 'o', 'n']**
l = [1,2,3]
print(l)
**Output: [1, 2, 3]**

Adding Elements to a List

If we want to add one item to the list we can use append() method.
It will add the item at the end of the list

l.append(4)
print(l)
**Output: [1, 2, 3, 4]**

If we want to add several items to a list we can use extend() method

l.extend([5,6,7])
print(l)
**output: [1, 2, 3,4,5, 6, 7]**

We can insert one item at a desired location using insert(index,value) method

l.insert(2,10)
print(l)
**Output: [1, 2, 10, 3, 4, 5, 6, 7]**

Deleting Elements from a List

If index is known we can use the pop() method, it will delete the item and stores in another variable.
If we give l.pop() it will remove the last item(right most element) in the list

a = l.pop(1)
print(l) ->gives [1, 10, 3, 4, 5, 6, 7]
print(a) ->gives 2

If the element is known we use the remove() method

l.remove(10)
print(l)
**Output: [1, 3, 4, 5, 6, 7]**

To clear the list we use clear() method. It will clear the contents of the list.

clear()

To delete total list we use delete() method. delete method will deletes entire list.

del()

sort() method is used for sorting the list in ascending order

l1 = [2,5,3,6,8,1]
l1.sort()
print(l1)
**Output: [1, 2, 3, 5, 6, 8]**

reverse() method used for reverse the contents of the list

l1.reverse()
print(l1)
**Output: [8, 6, 5, 3, 2, 1]**

List Comprehension

List comprehension is an elegant way to create a new list from an existing list in python.
Examle:

x = [x ** 2 for x in range(20)]
print(x)
**Output: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361**

Iterating through a list:
The For statement makes it easy to loop over the items in a list.

list1 = ['python','django','flask','pyramid',2018]
for elements in list1:
    print(element)
**Output: python, django, flask, pyramid, 2018**

If we want to access only the index , use range & len:

list1 = ['python','django','flask','pyramid',2018]
for index in range(len(list1)):
    print(index)
**Output: 0 1 2 3 4**

Some functions of List are

min() - returns the small item in a list
max() - returns the large item in a list
enumerate() - It returns position number & value. It will store as tuple
len() - This will give the length of a list
list() - converts an iterable to a list
sum()- returns the sum of elements in the list

Discover and read more posts from Sadhana Reddy
get started
post commentsBe the first to share your opinion
Sravan Singireddy
5 years ago

Good article…

Piotr Czajka
5 years ago

Hi, I really liked your article. But this:

x = (x ** 2 for x in range(20))

gives a generator expression, not a list, and passing it to print doesn’t print numbers

Eric Flores
5 years ago

Good catch. The reason is that this statement is enclosed in parentheses instead of square brackets. I should have noticed because the article is about lists, not tuples. But I didn’t notice the typo when reading the article until you pointed it out.

Sadhana Reddy
5 years ago

Thank you Eric Flores…

Sadhana Reddy
5 years ago

Piotr Czajka sorry for the mistake… Check it now

Jennifer Yeomans
5 years ago

Really insightful, thank you

Sadhana Reddy
5 years ago

Thank you Jennifer Yeomans

Show more replies