All You Need To Know About Python Lists

Posted on 24th April, 2017 by Hetal Vinchhi
All You Need To Know About Python Lists

Hello Guys...
Just like as our grocery list, wish-list, Let's see how to work with lists in Python. Python has a great built-in list type named "list". List is a sequence type in Python. We will see the actions like creating, accessing, modifying, iterating, sorting, cloning and deleting from the list.

Basics of List

List is type of sequence in Python. The sequence data type stores the data in sequence and each element is assigned an index which starts with 0. We can say list is an ordered set of data, which is enclosed within the square brackets. It is same as array in other languages but the main feature of list is that it can store elements of different data types. The elements are stored separated by comma in the list.

>>> l = [ 5, "Hello", 2.2]

The above list contains three elements.
The first one is int located at index 0.
The second one is string located at index 1.
The third one is float located at index 2.
The length of list is 3.

Let's see methods and attributes of the List in Python.

Creating List

new_list = [ 1, 2, "a", [3, 4] ]

The list in Python contains all kind of elements.

range()

The range function generates the sequence of integers.
range([start], stop, [increment])

start This is optional parameter. Default is 0
stop The stop value for the range
increment The increment can be positive or negative. Default is 1


>>> range(5)
[0, 1, 2, 3, 4]
>>> range(2, 5)
[2, 3, 4]
>>> range(1, 10, 2)
[1, 3, 5, 7, 9]
>>> range(5, 0, -1)
[5, 4, 3, 2, 1]

Accessing List Elements

We can access the list elements by its index. The index starts with 0.

	
>>> new_list = [1, 2, "a", [3, 4]]
>>> print(new_list[1])
2
	

Negative Index

To access the elements from the end of the list to the backward, the negative index is used. The index value -1 indicates the last element in the list.

Slicing List

The subset of the list is called slice. We can slice a list by specifying two indexes. It will inclusively take the first argument as index and will take the second one exclusively.

		
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> sliced = lst[2:8]
>>>print(sliced)
[3, 4, 5, 6, 7, 8]
		
	
Slicing Shorthand
lst[:3]

The above example is same as lst[0:3]. It will start index from 0 and will go up to 3 elements exclusively.

lst[6:]

It is same as lst[6:len(lst)], which will start from the given index 6 and will take elements upto the end.

lst[:]

If both slices are left, it will make a new copy(clone) of lst including all the elements.

Looping Over Lists

In Python, the list is considered as iterable, which can be iterated using for loop. The template of for loop is given as below.

		
for <item> in <iterable>:
	<body>
	
<item> : item is a  loop variable
<iterable> : it is the list to be iterated.
<body> : body to be executed.

	

>>> days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
for day in days:
	print(day)

Searching In List

Use of 'IN' Operator

To check if the given value is inside the list or not, we can use the 'in' operator.

	
>>> if 5 in l:
	print("yes")

	

Use of index() method

The index method finds the first occurrence of an element in the list. If any element occurs more than two times, it will give index of only first occurrence of the element.

		
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> lst.index(5)
4
>>> lst.index(10)

	lst.index(10)
ValueError: 10 is not in list
		

If given value is not found, Python raises an exception.

Mutability - Modifying List

The list is a mutable data type in Python. If we can change the value of a variable after its creation, it is considered mutable.

Editing Elements

	
>>> my_list = ["Banana", "Cake", "Juice"]
>>> print(my_list)
['Banana', 'Cake', 'Juice']
>>> my_list[1] = "Black Forest Cake"
>>> print(my_list)
['Banana', 'Black Forest Cake', 'Juice']
>>> my_list[1:3] = ["Apple", "Vanilla Cake"] # use of slice operator
>>> print(my_list)
['Banana', 'Apple', 'Vanilla Cake']
	

Adding Elements

apppend() method

The append method can be used to add elements into the list at the end of the list.


>>> my_list = []
>>> my_list.append(1)
>>> my_list[1] = "Hello"

my_list[1] = "Hello" IndexError: list assignment index out of range The append method adds a variable which can be of any type. There is no element at index 1. So it throws error "index out of range". We can set "hello" by using append method.

insert() Method

To add element at specific position, we can use the insert method.


>>> my_list = ['a', 'b', 'c', 'd', 'e']
>>> print(my_list)
['a', 'b', 'c', 'd', 'e']

>>> my_list.insert(2, 'bb')
>>>print(my_list)
['a', 'b', 'bb', 'c', 'd', 'e']

extend() method

The extend method concats the lists. The argument of the extend method must be of list type. It adds each element of the given list into the original list.


>>> my_list.extend(["f","g"])
>>> my_list
['a', 'b', 'bb', 'c', 'd', 'e', 'f', 'g']

Deleting Elements

Using DEL Keyword

To delete the elements in the list, del is used.


>>> new_list = [1, 2, 3, 4, 5, 6]
>>> del new_list[2]
>>> new_list
[1, 2, 4, 5, 6]
>>> del new_list[2:3]
>>> new_list
[1, 2, 5, 6]

Using remove() method

remove() method removes the occurrence of given value from the list. It will remove only first occurrence of the given value. If the value to remove is not found, Python will raise the exception.


>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> lst.remove(9)
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 0]
>>> lst.remove(10)
    lst.remove(10)
ValueError: list.remove(x): x not in list

Use of pop() method

The pop() method is used to remove the last element of the list if no index is specified otherwise it will remove element given at the specified index. It will also return the removed element.


>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> lst.pop()
0
>>> lst.pop(2)
3
>>>lst
[1, 2, 4, 5, 6, 7, 8, 9]

Cloning and Alias of List

Let's have two lists.


>>> a = [1,2,3]
>>> b = [1,2,3]

The object reference is as given below.

Memory allocation for objects

Here, a and b refers to the different objects and refers to different reference.


>>> if a == b:
	print("a equals b")
else:
	print("a not equal to b")
a equals b

This indicates that the values of the two lists are same


>>> if a is b:
	print("a equals b")
else:
	print("a not equal to b")
a not equal to b

The above statement states that a and b have equal content but they are not the same object.

Now Let's check the same code of equality and for the same object by changing the line to given below

>>> a = b = [1,2,3]

here, a and b refer to the same object. In this case b is alias of a.

The object reference is as given below.

Memory allocation for objects >>> c = a[:]

The above statement creates the clone of a into c which does not refer to the same reference but initially both have same values.

Sorting List

It is very easy to sort the list using the sorted method. The sorted method returns a new list with sorted order. It takes list as an argument.


>>> a = [9, 5, 6, 11]
>>> b = sorted(a)
>>> print(a)
[9, 5, 6, 11]
>>> print(b)
[5, 6, 9, 11]

Bonus Point

Concatenate

We can concat two lists using the + operator.


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

Repeating List Elements With *


>>> ["Hello"] * 4 
["Hello" , "Hello" , "Hello" , "Hello"]

Share Via:

Leave Comment

Assignment Solution Guru

Enter your Email ID to receive this Free Solution

We will not disclose your email address to anyone. Visit our Privacy Policy page for more information.

Thank You

Your download will start automatically...

Deals of the Day