Python Lists

List is a collection data structure which is ordered and changeable. If you want to represent a group of individual objects as a single entity where insertion order preserved and duplicates are allowed, then you should go for List. 

  • Insertion order preserved.
  • Duplicate objects are allowed
  • Heterogeneous objects are allowed.
  • Growable in nature
  • Values should be enclosed within square brackets
  • List is dynamic because based on our requirement we can increase the size and decrease the size.
  • In List the elements will be placed within square brackets and with comma separator.

You can differentiate duplicate elements by using index and you can preserve insertion order by using index. Hence index will play very important role.

Python supports both positive and negative indexes.

  • Positive index means from left to right.
  • Negative index means right to left.
>>> list = [10,"A","B",20, 30, 10]

>>> print(list)
-6      -5   -4     -3    -2      -1
10     A    B    20   30   10
 0        1     2      3      4       5

Note : List objects are mutable.i.e we can change the content.

Creation of List Objects

We have different methods to create a list.

  • You can create empty list object as follows:
>>> list=[]
>>> print(list)
[]

>>> print(type(list))
<class 'list'>
  • If you already know elements then you can create by putting those elements in this list as follows:
      list=["Alphs",10,20,30,40]
  • Dynamic input : You can create lists with dynamic inputs as follows:
list=eval(input("Enter List:"))
print(list)
print(type(list))

You can use any Python IDE (Integrated Development Environment) Editors. PyCharm is widely popular. You can install PyCharm in your machine. Paste above lines in in your favourite editor.

Enter List:[10,20,30,40]
[10, 20, 30, 40]
<class 'list'>
  • list() function : A list can be created using list() function.
l=list(range(0,10,2))
print(l)
print(type(l))

Output

[0, 2, 4, 6, 8]
<class 'list'>

Another example is

s="ravi"
l=list(s)
print(l)

Output

['r', 'a', 'v', 'i'']
  • split() function : Using split() function we can create list,
s="Learning Python is very very easy !!!"
l=s.split()
print(l)
print(type(l))

Output

['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']
<class 'list'>

Note : Sometimes we can take list inside another list, such type of lists are called nested lists.

[10,20,[30,40]]  ---> Nested List

Accessing Elements of List

We can access elements of the list either by using index or by using slice operator(:).

By using index

List follows zero based index ie. index of first element is zero. List supports both +ve and -ve indexes.

  • +ve index meant for Left to Right
  • -ve index meant for Right to Left

list=[10,20,30,40,50,60]

-6      -5     -4      -3    -2      -1
10     20   30   40   50   60
 0        1      2        3      4       5

print(list[0]) ==> 10
print(list[-1]) ==> 40
print(list[10]) ==> IndexError: list index out of range.

By Using Slice Operator

The Basic syntax of slice operator as follows:

list2= list1[start:stop:step]

  • Start  -> It indicates the index where slice has to start (default value is 0)
  • Stop  ->  It indicates the index where slice has to end (default value is max allowed index of list ie. length of the list)
  • Step  ->  Increment value (default value is 1)
n= [1,2,3,4,5,6,7,8,9,10]

print(n[2:7:2])     ==> [3, 5, 7]
print(n[4::2])       ==> [5, 7, 9]
print(n[3:7])         ==> [4, 5, 6, 7]
print(n[8:2:-2])   ==> [9, 7, 5]
print(n[4:100])    ==> [5, 6, 7, 8, 9, 10]

Change Item Value of a List (List vs Mutability)

Once we creates a List object, we can modify its content. Hence List objects are mutable.

n=[10,20,30,40]
print(n) ==> [10, 20, 30, 40]

n[1]=777
print(n) ==> [10, 777, 30, 40]

Traversing the Elements of Lists

The sequential access of each element in a list is called traversal.

By using while loop

n=[0,1,2,3,4,5,6,7,8,9,10]
i=0
while i<len(n):
    print(n[i])
    i=i+1

Output

0
1
2
3
4
5
6
7
8
9
10

By using for loop

We can use for loop in lists as well.

n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
    print(n1)

output

0
1
2
3
4
5
6
7
8
9
10

To display only even Numbers

We can get only even numbers from a list using for loop.

n=[0,1,2,3,4,5,6,7,8,9,10]
for n1 in n:
    if n1%2==0:
print(n1)

Output

0
2
4
6
8
10

Important functions of List

To get information about list, we can use below functions,

len() fucntion

This function returns the number of elements present in the list.

list=[10,20,30,40]

print(len(list)) ==> 4

count() function

It returns the number of occurrences of specified item in the list.

list = [1,2,2,2,2,3,3]

print(list.count(1))   ==> 1
print(list.count(2))  ==> 4
print(list.count(3))  ==> 2
print(list.count(4))  ==> 0

index() function

It returns the index of first occurrence of the specified item.

list = [1,2,2,2,2,3,3]

print(list.index(1)) ==> 0
print(list.index(2)) ==> 1
print(list.index(3)) ==> 5
print(list.index(4)) ==> ValueError: 4 is not in list

If the specified element not present in the list then we will get ValueError.

Manipulating elements of a List

append() function

We can use append() function to add item at the end of the list.

list=[]
list.append("x")
list.append("y")
list.append("z")
print(list)

Output

['x', 'y', 'z']

insert() function

You can insert item at specified index position using index() function.

list=[1,2,3,4,5]
list.insert(1,888)
print(n)

Output

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

If the specified index is greater than maximum index then element will be inserted at last position. If the specified index is smaller than minimum index then element will be inserted at first position.

list = [1,2,3,4,5]
list.insert(10,777)
list.insert(-10,999)
print(n)

Output

[999, 1, 2, 3, 4, 5, 777]

extend() function

We can add all items of one list to another list using extend() function.

list1.extend(list2) –> all items present in list2 will be added to list1

order1=["Apple","Banana","Orange"]
order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)

Output

['Apple', 'Banana', 'Orange', 'RC', 'KF', 'FO']

remove() function

We can use this function to remove specified item from the list. If the item present multiple times then only first occurrence will be removed.

list=[10,20,10,30]
list.remove(10)
print(n)

Output

[20, 10, 30]

If the specified item not present in list then we will get ValueError.

list=[10,20,10,30]
n.remove(40)
print(n)

Output

ValueError: list.remove(x): x not in list

pop() function

It removes and returns the last element of the list. This is only function which manipulates list and returns some element.

list=[10,20,30,40]
print(list.pop())
print(list.pop())
print(list)

Output

40
30
[10, 20]

If the list is empty then pop() function raises IndexError

n=[]

print(n.pop()) ==> IndexError: pop from empty list

Ordering elements of List

reverse() function

We can use to reverse() order of elements of list.

list=[10,20,30,40]
list.reverse()
print(n)

Output
[40, 30, 20, 10]

sort() function

In list by default insertion order is preserved. If want to sort the elements of list according to default natural sorting order then we should go for sort() method.

  • For numbers  ==> default natural sorting order is Ascending Order
  • For Strings     ==>  default natural sorting order is Alphabetical Order
list1=[20,5,15,10,0]
list1.sort()
print(list1) #  [0,5,10,15,20]

list2 = ["Dog","Banana","Cat","Apple"]
list2.sort()
print(list2) # ['Apple','Banana','Cat','Dog']

clear() function

We can use clear() function to remove all elements of List.

list=[10,20,30,40]
print(list)
list.clear()
print(n)

Output

[10, 20, 30, 40]
[]

Joining two lists

We can use + to concatenate or add two lists into a single list.

list1 = [10,20,30]
list2 = [40,50,60]
list = list1 + list2
print(list1) 

Output

[10,20,30,40,50,60]

Functions used with List 

Python has a set of built-in methods that you can use with lists.

Functions Description
append()  This function adds an element at the end of the list
clear()  This function removes all the elements from the list
copy()  It returns a copy of the list
count()  It returns the number of elements with the specified value
extend()  Add the elements of a list to the end of the current list
index()  It returns the index of the first element with the specified value
insert()  It adds an element at the specified position
pop()  It removes the element at the specified position
remove()  It removes the item with the specified value
sort()   It sorts the list
reverse() Reverses the order of the list

Read Also : How to Install Pycharm IDE for Windows and Create First Python Project

 

Share on:

Ravindra Kumar

Hi, This is Ravindra. I am founder of TheCodeCloud. I am AWS Certified Solutions Architect Associate & Certified in Oracle Cloud as well. I am DevOps and Data Science Enthusiast.

Recommended Reading..

2 thoughts on “Python Lists”

  1. Pingback: Python Tuple

Leave a Comment