Alphalearningschool
        

<<< Prev

Next >>>

Up
Python List

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. 

How to Create Python List?

To create python list of items, you need to mention the items, separated by commas, in square brackets. This is the python syntax you need to follow. Then assign it to a variable. Remember once again, you don’t need to declare the data type, because Python is dynamically-typed.

>>> colors=['red','green','blue']

 A Python list may hold different types of values.

>>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]

 A list may have python list. 

>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
>>> languages
['English'], ['Gujarati'], ['Hindi'], 'Romanian', 'Spanish']
>>> type(languages[0])
<class 'list'>

 A list may also contain tuples or so. 

>>> languages=[('English','Albanian'),'Gujarati','Hindi','Romanian','Spanish']
>>> languages[0]
('English' , 'Romanian')
>>> type(languages[0])
<class 'tuple'>

 

>>> languages[0][0]='Albanian'
Traceback (most recent call last):
File "<pyshell#24>”, line 1, in <module>
languages[0][0]='Albanian'
TypeError: 'tuple' object does not support item assignment

 

How to Access Python List?

To access a Python list as a whole, all you need is its name. 

>>> days
['Monday', 'Tuesday', 'Wednesday', 4, 5, 6, 7.0]

 Or, you can put it in a print statement.

 

>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
>> print(languages)
[['English'], ['Gujarati'], ['Hindi'], 'Romanian', 'Spanish']

 

To access a single element, use its index in square brackets after the list’s name. Indexing begins at 0.

>>> languages[0]
['English']

 

An index cannot be a float value. 

>>> languages[1.0]

 

Example:

a = [5,10,15,20,25,30,35,40]

# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])


O/P-
a[2] =  15
a[0:3] =  [5, 10, 15]
a[5:] =  [30, 35, 40]

 

Slicing a Python List

When you want only a part of a Python list, you can use the slicing operator []. 

>>> indices=['zero','one','two','three','four','five']
>> indices[2:4]
['two', 'three']

 This returns items from index 2 to index 4-1 (i.e., 3) 

>>> indices[:4]
['zero', 'one', 'two', 'three']

 This returns items from the beginning of the list to index 3. 

>>> indices[4:]
['four', 'five']

 It returns items from index 4 to the end of the list in Python. 

>>> indices[:]
['zero', 'one', 'two', 'three', 'four', 'five']

 This returns the whole list.

Negative indices- The indices we mention can be negative as well. A negative index means traversal from the end of the list. 

>>> indices[:-2]
['zero', 'one', 'two', 'three']

 This returns item from the list’s beginning to two items from the end. 

>>> indices[1:-2]
['one', 'two', 'three']

 It returns items from the item at index 1 to two items from the end. 

>>> indices[-2:-1]
['four']

 This returns items from two from the end to one from the end.

>>> indices[-1:-2]
[]

 This returns an empty Python list, because the start is ahead of the stop for the traversal.

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']

 

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']

 

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']

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.

>>> color[4]='holographic'
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
color[4]='holographic'
NameError: name 'color' is not defined

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.

a. 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

 

b. 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.

c. Deleting a single element

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

>>> del colors[0]
>>> colors
['gold', 'holographic']

 

Multidimensional Lists in Python

You can also put a list in a list. Let’s look at a multidimensional list.

>>>grocery_list=[['caramel','P&B','Jelly'],['onions','potatoes'],['flour','oil']]
>>> grocery_list
[['caramel', 'P&B', 'Jelly'], ['onions', 'potatoes'], ['flour', 'oil']]

 This is a grocery Python list with lists in it, where the lists are according to a category. Or, you can choose to go deeper.

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

 To access the element 4 here, we type the following code into the shell.

>>> a[0][1][1]
4

 

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

a. 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'

 

b. Membership

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

>>> 1 in a
True
>>> 2 not in a
False

 

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]

Python List Operations

a. 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'

 

b. Membership

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

>>> 1 in a
True
>>> 2 not in a
False

 

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]

 

 Built-in List Functions & Methods

Python includes the following list functions −

Sl no

Function with Description

1

cmp(list1, list2)

Compares elements of both lists.

2

len(list)

Gives the total length of the list.

3

max(list)

Returns item from the list with max value.

4

min(list)

Returns item from the list with min value.

5

list(seq)

Converts a tuple into list.

 

Python includes following list methods

 

S l No.

Methods with Description

1

list.append(obj)

Appends object obj to list

2

list.count(obj)

Returns count of how many times obj occurs in list

3

list.extend(seq)

Appends the contents of seq to list

4

list.index(obj) 

Returns the lowest index in list that obj appears

5

list.insert(index, obj)

Inserts object obj into list at offset index

6

list.pop(obj=list[-1])

Removes and returns last object or obj from list

7

list.remove(obj)

Removes object obj from list

8

list.reverse()

Reverses objects of list in place

9

list.sort([func])

Sorts objects of list, use compare func if given