Introduction to various types of Python – Lists

If you are interested to learn about the python strings

The most basic data structure in Python is the sequence. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. Each element of a sequence is assigned a number – its position or index. The first index is zero, the second index is one, and so forth. Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial. There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.

What does * list mean in Python?

It’s essentially a combination of tuple/list unpacking and *args iterable unpacking. Each iterable is getting unpacked on each iteration of the for loop

Python Lists

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

Creating a list is as simple as putting different comma-separated values between square brackets. For example −

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

Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Accessing Values in Lists

To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

#!/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]

When the above code is executed, it produces the following result −

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

List Items

List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items will not change.

Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

Allow Duplicates

Since lists are indexed, lists can have items with the same value:

Example

Lists allow duplicate values:

this list = ["apple", "banana", "cherry", "apple", "cherry"]<br>print(thislist)

List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]<br>print(len(thislist)

List Items – Data Types

List items can be of any data type:

Example

String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]<br>list2 = [1, 5, 7, 9, 3]<br>list3 = [True, False, False]

A list can contain different data types:

Example

A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

type()

From Python’s perspective, lists are defined as objects with the data type ‘list’:<class ‘list’>

Example

What is the data type of a list?

mylist = ["apple", "banana", "cherry"]<br>print(type(mylist))

The list() Constructor

It is also possible to use the list() constructor when creating a new list.

Example

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets<br>print(thislist)

Python Collections (Arrays)

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

Updating Lists

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For 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]

Note − append() method is discussed in subsequent section.

When the above code is executed, it produces the following result −

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

Delete List Elements

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example −

#!/usr/bin/python

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

When the above code is executed, it produces following result −

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

Note − remove() method is discussed in subsequent section.

Basic List Operations

Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string. In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.

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

Because lists are sequences, indexing and slicing work the same way for lists as they do 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

Python – Access List Items

Access Items

List items are indexed and you can access them by referring to the index number:

Example

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]<br>print(thislist[1])

Note: The first item has index 0.

Negative Indexing

Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]<br>print(thislist[-1])

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items.

Example

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]<br>print(thislist[2:5])

Python – Change List Items

Change Item Value

To change the value of a specific item, refer to the index number:

Example

Change the second item:

thislist = ["apple", "banana", "cherry"]<br>thislist[1] = "blackcurrant"<br>print(thislist)

Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:

Example

Change the values “banana” and “cherry” with the values “blackcurrant” and “watermelon”:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]<br>thislist[1:3] = ["blackcurrant", "watermelon"]<br>print(thislist)

If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Example

Change the second value by replacing it with two new values:

thislist = ["apple", "banana", "cherry"]<br>thislist[1:2] = ["blackcurrant", "watermelon"]<br>print(thislist)

Note: The length of the list will change when the number of items inserted does not match the number of items replaced.

If you insert less items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly:

Example

Change the second and third value by replacing it with one value:

thislist = ["apple", "banana", "cherry"]<br>thislist[1:3] = ["watermelon"]<br>print(thislist)

Insert Items

To insert a new list item, without replacing any of the existing values, we can use the insert() method. The insert() method inserts an item at the specified index:

Example

Insert “watermelon” as the third item:

thislist = ["apple", "banana", "cherry"]<br>thislist.insert(2, "watermelon")<br>print(thislist)

Python – Add List Items

Append Items

To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]<br>thislist.append("orange")<br>print(thislist)

Insert Items

To insert a list item at a specified index, use the insert() method. The insert() method inserts an item at the specified index:

Example

Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]<br>thislist.insert(1, "orange")<br>print(thislist)

Note: As a result of the examples above, the lists will now contain 4 items.

Extend List

To append elements from another list to the current list, use the extend() method.

Example

Add the elements of tropical to thislist:

thislist = ["apple", "banana", "cherry"]<br>tropical = ["mango", "pineapple", "papaya"]<br>thislist.extend(tropical)<br>print(thislist).

The elements will be added to the end of the list.

Add Any Iterable

The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).

Example

Add elements of a tuple to a list:

thislist = ["apple", "banana", "cherry"]<br>thistuple = ("kiwi", "orange")<br>thislist.extend(thistuple)<br>print(thislist)

Python – Remove List Items

Remove Specified Item

The remove() method removes the specified item.

Example

Remove “banana”:

thislist = ["apple", "banana", "cherry"]<br>thislist.remove("banana")<br>print(thislist)

Remove Specified Index

The pop() method removes the specified index.

Example

Remove the second item:

thislist = ["apple", "banana", "cherry"]<br>thislist.pop(1)<br>print(thislist)

If you do not specify the index, the pop() method removes the last item.

Example

Remove the last item:

thislist = ["apple", "banana", "cherry"]<br>thislist.pop()<br>print(thislist)

The del keyword also removes the specified index:

Example

Remove the first item:

thislist = ["apple", "banana", "cherry"]<br>del thislist[0]<br>print(thislist)

The del keyword can also delete the list completely.

Example

Delete the entire list:

thislist = ["apple", "banana", "cherry"]<br>del thislist

Clear the List

The clear() method empties the list. The list still remains, but it has no content.

Example

Clear the list content:

thislist = ["apple", "banana", "cherry"]<br>thislist.clear()<br>print(thislist)
Introduction to various types of Python – Lists
Show Buttons
Hide Buttons