Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python Lists Tutorial with examples



Hello guys! Welcome back to another section of my tutorial on Python. In this tutorial post, we are going to be studying about the Python Lists.

The most basic data structure in Python is the sequence. Each of the element of the sequence is been assigned a number - It's position or index. The first index is zero, the second index is one, and so forth.

Python programming has six built-in types of sequences, but the most common ones are the lists and turples, we would only be discussing about the lists in this tutorial. Turples will be discussed in my subsequent tutorials.

There are several things you can do with all the Python sequence types. They include indexing, adding, slicing, multiplying,  as well as checking for membership. In addition, Python has built-in functions used for finding the length of a sequence and for finding its largest and smallest elements.

RECOMMENDED POST: Python Strings Tutorial

Python Lists

The list is the most versatile datatype available in Python. It can be written as a list of comma separated values between square brackets. Important thing about a list is that items in a list need not to be of the same type.

Example

Creating a list in Python is as simple as putting various comma separated values into square brackets. Below is an example -

list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

Similar to string indices, list indices starts at 0. List can also be sliced, concatenated, and so on.

Accessing Values in Lists

In order to access values in lists, use the square brackets for slicing along with the index or the indices to obtain values available at that index.

Example

Below is a very simple example which illustrates how to access lists values in Python -

#!/usr/bin/python

list1
= ['physics', 'chemistry', 1997, 2000];
list2
= [1, 2, 3, 4, 5, 6, 7 ];
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

Output

Below is the output of the above example -

list1[0]:  physics
list2[1:5]: [2, 3, 4, 5]

RECOMMENDED: Python Numbers

Updating Lists

You can update a single or multiple elements of lists by giving the slice on the left hand side of the Python assignment operator, and you can add to the elements in a list with the append() method.

Example

The following below is a very simple example -

#!/usr/bin/python

list
= ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list
[2] = 2001;
print "New value available at index 2 : "
print list[2]

Output

Below is the output of the above example -

Value available at index 2 :
1997
New value available at index 2 :
2001

Deleting Lists Elements

To delete a list element, you can use either the del statement if you know exact element(s) you are deleting or the remove() method if you do not know the element you deleting.

Example

The following below is a simple example -

#!/usr/bin/python

list1
= ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1

Output

Below is the output of the above example -

['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]

RECOMMENDED: Python Nested If Statement 

Basic List Operations

Python lists respond to the + and * operators much like strings. These operators means concatenation and repetition here too, except that the result is a new list and not a string.

Infact, lists also responds to all the general sequence operations that we used on strings in our past tutorial on Python Strings.

Python ExpressionResultsDescription
len([1, 2, 3])3Length
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
['Hi!'] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!']Repetition
3 in [1, 2, 3]TrueMembership
for x in [1, 2, 3]: print x,1 2 3Iteration

Indexing, Slicing, and Matrixes

Since lists are sequences, indexing and slicing work the same way for lists as they do work for strings.

Assuming following input -

L = ['spam', 'Spam', 'SPAM!']

Python ExpressionResultsDescription
L[2]SPAM!Offsets start at zero
L[-2]SpamNegative: count from the right
L[1:]['Spam', 'SPAM!']Slicing fetches sections

RECOMMENDED POST: For Loop Statements in Python


Built-in List Functions in Python 
Python includes the following lists functions -

Sr.No.Function with Description
1cmp(list1, list2)
Compares elements of both lists.
2len(list)
Gives the total length of the list.
3max(list)
Returns item from the list with max value.
4min(list)
Returns item from the list with min value.
5list(seq)
Converts a tuple into list.


Built-in List Methods 
Python includes the following list methods -

Sr.No.Methods with Description
1list.append(obj)
Appends object obj to list
2list.count(obj)
Returns count of how many times obj occurs in list
3list.extend(seq)
Appends the contents of seq to list
4list.index(obj)
Returns the lowest index in list that obj appears
5list.insert(index, obj)
Inserts object obj into list at offset index
6list.pop(obj=list[-1])
Removes and returns last object or obj from list
7list.remove(obj)
Removes object obj from list
8list.reverse()
Reverses objects of list in place
9list.sort([func])
Sorts objects of list, use compare func if given

RECOMMENDED POST: Python Basic Syntax Tutorial

Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial, we are going to be discussing about the Python Lists cmp() Method.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.


This post first appeared on Web Design Tutorialz, please read the originial post: here

Share the post

Python Lists Tutorial with examples

×

Subscribe to Web Design Tutorialz

Get updates delivered right to your inbox!

Thank you for your subscription

×