What is Python Lists?

Published by Anshul Verma on

Unlike C++ or Java, Python Programming Language doesn’t have arrays. To hold a sequence of values, then, it provides the ‘list’ class. A Python list can be seen as a collection of values. Lists are Python’s most flexible ordered collection object type. It can also be referred to as a sequence that is an ordered collection of objects that can host objects of any data type, such as Python Numbers, Python Strings and nested lists as well. Lists are one of the most used and versatile Python Data Types. In this module, we will learn all about lists in order to get started with them.

Python List with Examples - A Complete Python List Tutorial

Following is the list of all topics that are going to be covered in this module :

Creating a Lists in python

A list can be created by putting the value inside the square bracket, and values are separated by commas.

Unlike strings, lists can contain any sort of objects: numbers, strings, and even other lists. Python lists are:

  • Ordered collections of arbitrary objects
  • Accessed by offset
  • Arrays of object references
  • Of variable length, heterogeneous, and arbitrarily nestable
  • Of the category, mutable sequence
  • Data types in which elements are stored in the index basis with starting index as 0
  • Enclosed between square brackets ‘[]’

Example:

list1 = [1,2,3,4,5]

list2 = [“hello”, “coder”]

Creating Multi-dimensional Lists in Python

A list can hold other lists as well which can result in multi-dimensional lists. Next, we will see how to create multi-dimensional lists, one by one.

One-dimensional Lists in Python:

init_list = [0]*3

print(init_list)

Output:

[0, 0, 0]

Two-dimensional Lists In Python:

two_dim_list = [ [0]*3 ] *3

print(two_dim_list)

Output:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Three-dimensional Lists in Python:

two_dim_list = [[ [0]*3 ] *3]*3

print(two_dim_list)

Output:

[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],

[[0, 0, 0], [0, 0, 0], [0, 0, 0]],

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]

Python List Comprehension

Python List comprehension helps in constructing lists in a completely natural and easy way.

List = [1,2,3,4,5]

List1 = [ i for i in range(5)]

print(List1)

Output:

[0, 1, 2, 3, 4]

Complicated Python List Comprehension Examples

Example 1:

print ([a+b for a in ‘mug’ for b in ‘lid’])

Output:

[‘ml’, ‘mi’, ‘md’, ‘ul’, ‘ui’, ‘ud’, ‘gl’, ‘gi’, ‘gd’]

Example 2:

list_fruit = [“Apple”,”Mango”,”Banana”,”Avocado”]

first_letters = [ fruits[0] for fruits in list_fruit ]

print(first_letters)

Output:

[‘A’, ‘M’, ‘B’, ‘A’]

List Extension

Python allows lists to resize in many ways. We can do that just by adding two or more of them.

Example:

two_dim = [[0]*3 for i in range(3)]print(two_dim)

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

two_dim[0][2] = 1

print(two_dim)

Output:

[[0, 0, 1], [0, 0, 0], [0, 0, 0]]

  • extend(): 

Alternately, we can do extension by using the extend() method. See the following example:

L1 = [‘a’, ‘b’]

L2 = [‘c’, ‘d’]

L1.extend(L2)

print(L1)

Output:

[‘a’, ‘b’, ‘c’, ‘d’]

  • append(): 

Next, we can append a value to a list by calling the append() method. See the following example:

L1 = [‘a’, ‘b’]

L2 = [‘c’, ‘d’]

L1.extend(L2)

print(L1)

Output:

[‘a’, ‘b’, ‘c’, ‘d’]

Accessing Lists in Python

Much similar to strings, we can use the index number to access items in lists as shown below.
Example:

list1 = [1,2,3,4,5]

Accessing a List Using Reverse Indexing

To access a list in reverse order, we have to use indexing from −1, −2…. Here, −1 represents the last item in the list.

print(list1[-1])

print(list1[-3])

Output:

5

3

Common List Operations in Python

Following is the list of some of the most common list operations in Python, along with their descriptions and examples.

Slicing Python Lists

Slicing operation is used to print a list up to a specific range. We can use slice operation by including the starting index and ending index of the range that we want to print separated by a colon as shown below:

list1[2:4]

output:

[3, 4]

list1[2:-1]

output:

[3, 4]

list1[:2]

output:

[1, 2]

Iterating through Python Lists

Iterating is quite simple in lists. We can just use Python for loop to iterate, as shown below:

list1 = [1,2,3,4,5]

for element in list1:

print(element)

Output:

1

2

3

4

5

Update or Add Elements in a Python List

We can update a particular item or multiple items of a list by using the slice operation, and then add an element using the append () method as shown below.

Example:

list1[4] = ‘number’print(list1)list1[4:7] = [“Apple”,”Mango”,”Banana”]

print(list1)list1.insert(0,33)

print(list1)list1.insert(6,29)

print(list1)

Output:

[1, 2, 3, 4, ‘number’]

[1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]

[33, 1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]

[33, 1, 2, 3, 4, ‘Apple’, 29, ‘Mango’, ‘Banana’]

Remove elements from list in python

There are three ways of removing elements from lists. We can either use the del keyword to remove a particular element or we can use the remove () method, and the last way is using the pop () method, as shown in the following code block:

list1 = [1,2,3,4,5]

del list1[2]

list2 = [1,2,3,4,5]

list2.remove(4)

print(list2)

list3 = [1,2,3,4,5]

print(list3.pop(1))

print(list3)

Output:

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

2

[1, 3, 4, 5]

Remove duplicates from lists in python

Here’s an example of list where some items are repeating. Let us see how we can remove duplicates from list in python.

mylist = [“a”, “b”, “c”, “d”, “c”]

mylist = list(dict.fromkeys(mylist))

output:

[“a”, “b”,”c”,”d”]

Reverse a list in python

lst = [10, 11, 12, 13, 14, 15]

lst.reverse()

print(lst)

output:

[15, 14, 13, 12, 11, 10]

Sorting Lists in Python

Python list implements the sort() method for ordering (in both ascending and descending order) its elements in place.

list1.sort()

Sorting in ascending order:

list1 = [1,3,2,4,5,9,6]

list1.sort()

print(list1)

output:

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

Sorting in descending order:

list1 = [1,3,2,4,5,9,6]

list1.sort(reverse=True)

print(list1)

output:

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

Python List Functions and Methods

Let’s understand different types of Python functions for lists through the following table that contains a list of different functions with their respective descriptions.

Method Description
min(list_name) Returns the minimum value from a list in Python
max(list_name) Returns the largest value from a list in Python
len(list_name) Returns the number of elements in a list in Python
cmp(list1,list2) Compares two lists in Python
list.reverse() Reverses a list in Python
list.sort Sorts a list in Python
list(sequence) Converts the sequence of a list in Python
list.append(value) Adds a value into a list in Python
list.remove(value) Removes a value from a list in Python

Reassigning a Python List (Mutable)

Python Lists are mutable. This means that you can reassign its items, or you can reassign it as a whole. Let’s take a new list.

>>> colors=[‘red’,’green’,’blue’]

l ) Reassigning the whole Python list

You can reassign a Python list by assigning it like a new list.

>>> colors=[‘caramel’,’gold’,’silver’,’occur’]

>>> colors

[‘caramel’, ‘gold’, ‘silver’, ‘occur’]

ll ) Reassigning a few elements

You can also reassign a slice of a list in Python.

>>> colors[2:]=[‘bronze’,’silver’]

>>> colors

[‘caramel’, ‘gold’, ‘bronze’, ‘silver’]

If we had instead put two values to a single one in the left, see what would’ve happened.

>>> colors=[‘caramel’,’gold’,’silver’,’occur’]

>>> colors[2:3]=[‘bronze’,’silver’]

>>> colors

[‘caramel’, ‘gold’, ‘bronze’, ‘silver’, ‘occur’]

colors[2:3] reassigns the element at index 2, which is the third element.

2:2 works too.

>>> colors[2:2]=[‘occur’]

>>> colors

[‘caramel’, ‘gold’, ‘occur’, ‘bronze’, ‘silver’]

lll ) Reassigning a single element

You can reassign individual elements too.

>>> colors=[‘caramel’,’gold’,’silver’,’occur’]

>>> colors[3]=’bronze’

>>> colors

[‘caramel’, ‘gold’, ‘silver’, ‘bronze’]

Now if you want to add another item ‘holographic’ to the list, we cannot do it the conventional way.

>>> colors[4]=’holographic’

Traceback (most recent call last):

File “<pyshell#2>”, line 1, in <module>

colors[4]=’holographic’

IndexError: list assignment index out of range

So, you need to reassign the whole list for the same.

>>> colors=[‘caramel’,’gold’,’silver’,’bronze’,’holographic’]

>>> colors

[‘caramel’, ‘gold’, ‘silver’, ‘bronze’, ‘holographic’]

How can we Delete a Python List?

You can delete a Python list, some of its elements, or a single element.

l ). Deleting the entire Python list

Use the del keyword for the same.

>>> del colors

>>> colors

Traceback (most recent call last):

File “<pyshell#51>”, line 1, in <module>

colors

NameError: name ‘colors’ is not defined

II ). Deleting a few elements

Use the slicing operator in python to delete a slice.

>>> colors=[‘caramel’,’gold’,’silver’,’bronze’,’holographic’]

>>> del colors[2:4]

>>> colors

[‘caramel’, ‘gold’, ‘holographic’]

>>> colors[2]

‘holographic’

Now, ‘holographic’ is at position 2.

III ). Deleting a single element

To delete a single element from a Python list, use its index.

>>> del colors[0]

>>> colors

[‘gold’, ‘holographic’]

IV ) Concatenation of Python List

The concatenation operator works for lists as well. It lets us join two lists, with their orders preserved.

>>> a,b=[3,1,2],[5,4,6]

>>> a+b

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

Python List Operations

I ) Multiplication

This is an arithmetic operation. Multiplying a Python list by an integer makes copies of its items that a number of times while preserving the order.

>>> a*=3

>>> a

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

However, you can’t multiply it by a float.

>>> a*3.0

Traceback (most recent call last):

File “<pyshell#89>”, line 1, in <module>

a*3.0

TypeError: can’t multiply sequence by non-int of type ‘float’

II ) Membership

You can apply the ‘in’ and ‘not in’ operators on a Python list.

>>> 1 in a

True

>>> 2 not in a

False

III ) Iterating on a list

Python list can be traversed with a for loop in python.

>>> for i in [1,2,3]:

if i%2==0:

print(f”{i} is composite\n”)

2 is composite

Python List Comprehension

You can create a new list just like you would do in mathematics. To do so, type an expression followed by a for statement, all inside square brackets. You may assign it to a variable. Let’s make a list for all even numbers from 1 to 20.

>>> even=[2*i for i in range(1,11)]

>>> even

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Optionally, you can add an if-statement to filter out items. If we want to change this list to hold only those items from 1 to 20 that are even and are divisible by 3, we write the following code.

>>> even=[2*i for i in range(1,11) if i%3==0]

>>> even

[6, 12, 18]

That’s all for the list in python. In our next blog we will cover complete “TUPLE” in python.

Till then, Stay Safe, Stay Happy & Keep Coding…

IF YOU WANT TO KNOW ABOUt DATA SCIENCE click here.

CONNECT WITH THE AUTHOR ON LINKEDIN.

VISIT OUR WEBSITE BRIGHTERBEES FOR MORE INTERESTING STUFFS ABOUT LEARNING.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

STAY CONNECT WITH US