Lists in Python

Introduction

The list is one of the four main built-in data structures available in the Python libraries. The other three are Tuples, Dictionaries, and Sets.

Lists are used to store multiple values of different data types in a single variable.
d4

The different elements in a list are stored simultaneously in the memory. Each element of a list is denoted by an index value which is used to access different elements of the list.

List characteristics

  • Ordered - List items are stored simultaneously and are thus ordered. New elements added will get stored at the end of the list.
  • Muteable - List elements can be modified. That is they can be changed and thus lists are mutable data structures.
  • Data types - Any data type can be stored in a list. A single list can store values of multiple data types as well.
  • Allows duplicate members

List creation

The easiest way to create a list is by simply writing the values, separated by commas, amidst a pair of ‘[]’ parentheses and storing it in a variable.

For example,

List1 = [ “a", 1, True, [1, 2, 5, 6, 9, 100, 103], 66.8]
print(List1)

Otherwise, a List constructor may be used to create a list. The list() function, available in the Python libraries, is used to build a list from any other data structure or data type. The variable/ data needs to be written within the parentheses.

For example,

list2 = list([40, “pop”])

Access Methods

Lists are ordered data structures. The elements are indexed. That is the elements in a list follow a certain order, every new element is added to the end of the list.

The first index of every list starts from 0 and ends at (n – 1), where n is the total number of elements in the list.

Methods to get elements from a list:

Using index numbers

For example,

listA = [1, 2, 5, 10]
print( listA[ 2 ] )

and the output stands,

5
Negative indexing

-1’ refers to the last element of the list, while ‘-2’ refers to the second last element, and so on. This method is also called reverse indexing.

For example,

listB = [1, 50, 66.3, “Humans”]
print( listB[ -1 ] )

and the output is,

“Humans”
Range of indexes

In a list, one can specify the starting and the ending indexes, and return a list of only the specified items within that range of indexes.

Syntax:

List_Name[ <starting index> : <end index> ]
List slicing excludes the end index value while slicing.

For example,

listC = [“a”, “b”,  23.2, “c”]
print( listC[ 1 : 3 ] )

output is,

[“b”, 23.2]	#starts from 1 index and selects till 2

For example, leaving out one of the end indexes,

print( listC[ 1 : ] )	#indicates all the items till the end of the list
print( listC[ : 3 ] )	#indicates all the items from the starting of the list

and the output being,

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

For example, negative range of indexes,

print( listC[ -3 : -1 ] )

the output is,

[“b”, 23.2]	#starts from -3 index and selects till -1
To check whether an item is present in a list

The ‘in’ keyword is used to check whether a value is present in a list or not.

For example,

listD = [55, “Mark”, 60]
if 60 in listD:
    print( “Yes” )

and the output is,

Yes		#since 60 is present in the list
Copying lists

Lists cannot be copied from one variable to another by simply writing list1 = list2. The copy() method creates a copy of the said list in the new variable quite like this,

list2 = list1.copy()

The list method can also be used.

List2 = list( List1 )
List index out of range

The IndexOutofRange error is thrown whenever an index that is beyond the length of the list is called.

listE = [1, 2, 3]
print( listE[ 4 ] )

The output of the above code shows an index out-of-range error.
d3

Adding or changing a list

A list can consist of any number of elements. Elements can be added to a list using four functions:

Append function

The append() function appends a single element at the end of a list.

listF = [1, 3, 5]
listF.append(6)
print( listF )

the output,

[1, 3, 5, 6]
Extend function

The extend() function can be used to add multi-element iterables to the end of a list. The iterable need not only be lists. They can be tuples, sets, or dictionaries, etc. too.

list1 = [1, 9, 15]
list1.extend( [ 5, 99 ] )
print( list1 )
list1.extend( (151, 664) )
print( list1 )

the output of which is,

[1, 9, 15, 5, 99]
[1, 9, 15, 5, 99, 151, 664]
Insert function

The insert() function is used to insert an element at a particular index in a list, provided that the index in the particular list exists.

list2 = [“apple”, “banana”, “orange”]
list2.insert(2, “guava”)
print( list2 )

the output being,

[“apple”, “banana”, “guava”, “orange”]
Concatenation and multiplication

The ‘+’ operator can be used to concatenate two lists, while the ‘*’ operator can be used to repeat a particular list several times.

list3 = [1, 2, 3]
list4 = [“fine”]
print( list3 + list4 )
print( list4 * 3 )

and the output being,

[1, 2, 3, “fine”]
[“fine”, “fine”, “fine”]

A list can be modified by simply choosing the list index and simply stating the new value with an ‘=’ sign.

listo = [“bus”, “car”, “bike”]
listo[ 1 ] = “taxi”
print( listo )

output,

[“bus”, “taxi”, “bike”]

A range of indexes can also be modified as follows.

listo[ 0 : 2 ] = [1, 3]
print( listo )

with output,

[1, 3, “bike”]

Deleting from a list

There are several ways to delete an element/ elements from a list.

Remove method

The remove() method removes a particular item from a list. It removes the first occurrence of the said item from the list.

Pop method

The pop() method is used to remove an item from the given location of a list. If the index is not given, then it deletes the last item on the list.

Del method

The del method can be used to remove both individual elements as well as clear out entire lists.

Clear method

The clear() method clears out the entire list thus rendering the entire list deleted.

Examples of the above methods are as follows:

List5 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
List5.remove(3)
print( List5 )
List5.pop()
print( List5 )
del List5[3]
print( List5 )
List5.clear()
print( List5 )

the outputs are,

[1, 2, 4, 5, 6, 7, 8, 9]
[1, 2, 4, 5, 6, 7, 8]
[1, 2, 4, 6, 7, 8]

and the last print statement will show a list not found error.

Traversing a list using loops

A list in Python can be iteratively traversed using a ‘for’ loop by using the ‘in’ keyword.

list7 = [“a”, “b”, “c”]
for a in list7:
print( a )

the outputs are as follows,

“a”
“b”
“c”

This ‘for’ loop method can be used in list comprehension too to print the elements of the said list.

[print(x) for x in list7]

the output being,

“a”

“b”

“c”

The len() function can be used to measure the length of a given list. It can be used to access different items in an array.

for i in range(len( list7 )):
    print( list7[ i ] )

the output is,

“a”
“b”
“c”

List comprehension

List comprehension enables a shorter and concise line of code to build a list from an existing list.

Syntax:

newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged. The iterable might be any iterable of convenience, ie. Tuples, objects, etc. The expression is the object to be added to the new list and can be manipulated therein.

List8 = [“a”, “b”, “c”]
List9 = [ i.upper() for i in List8 ]
print(List9)

the output being,

[“A”, “B”, “C”]

count()

Counts the number of occurrences of a particular value in a list.

list10 = [1, 1, 2, 3, 4, 5, 4, 4, 6, 7]

print( list10.count(4) )

output:

3
index()

Returns the index position of the first occurrence of the specified element.

list10 = [1, 1, 2, 3, 4, 5, 4, 4, 6, 7]

print( list10.index(4) )

output:

4
reverse()

Reverses the elements of the list.

list11 = [“a”, “b”, “c”]

print( list11.reverse() )

output:

[“c”, “b”, “a”]
sort()

The sort() function helps to sort lists in ascending order. The ‘reverse’ parameter, if set as ‘true’, then arranges the list in descending order. The ‘key’ parameter defines the function to be used for sorting.

list12 = [1, 5, 9, 4, 6, 2, 3, 8, 7]
list12.sort()
print( list12 )
list12.sort( reverse = true )
print( list12 )

output:

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

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

Tuples in Python

0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions