Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
46 views

Python List

Python has four main collection data types: lists, tuples, sets, and dictionaries. Lists are ordered and changeable collections that allow duplicate elements. Key properties of lists include being indexed and mutable. Common list operations include accessing elements by index, slicing lists, updating and adding elements, removing elements, and iterating over lists.

Uploaded by

Kamalakumar V
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Python List

Python has four main collection data types: lists, tuples, sets, and dictionaries. Lists are ordered and changeable collections that allow duplicate elements. Key properties of lists include being indexed and mutable. Common list operations include accessing elements by index, slicing lists, updating and adding elements, removing elements, and iterating over lists.

Uploaded by

Kamalakumar V
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

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 and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.

When choosing a collection type, it is useful to understand the properties of that


type. Choosing the right type for a particular data set could mean retention of
meaning, and, it could mean an increase in efficiency or security.

Python List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python consists
of six data-types that are capable to store the sequences, but the most common and
reliable type is the list.

A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets [].

A list can be define as below

L1 = ["John", 102, "USA"]

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

If we try to print the type of L1, L2, and L3 using type() function then it will come out to be a list.

print(type(L1))

print(type(L2))

Output:

<class 'list'>

<class 'list'>
Characteristics of Lists
The list has the following characteristics:

o The lists are ordered.


o The element of the list can access by index.
o The lists are the mutable type.
o A list can store the number of various elements.

Let's check the first statement that lists are the ordered.

a = [1,2,"Peter",4.50,"Ricky",5,6]

b = [1,2,5,"Peter",4.50,"Ricky",6]

a ==b

Output:

False

Both lists have consisted of the same elements, but the second list changed the index position of the 5th
element that violates the order of lists. When compare both lists it returns the false.

Lists maintain the order of the element for the lifetime. That's why it is the ordered collection of objects.

a = [1, 2,"Peter", 4.50,"Ricky",5, 6]

b = [1, 2,"Peter", 4.50,"Ricky",5, 6]

a == b

Output:

True

Let's have a look at the list example in detail.

emp = ["John", 102, "USA"]

Dep1 = ["CS",10]

Dep2 = ["IT",11]

HOD_CS = [10,"Mr. Holding"]

HOD_IT = [11, "Mr. Bewon"]

print("printing employee data...")

print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))


print("printing departments...")

print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%


(Dep1[0],Dep2[1],Dep2[0],Dep2[1]))

print("HOD Details ....")

print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]))

print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]))

print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))

Output:

printing employee data...

Name : John, ID: 102, Country: USA

printing departments...

Department 1:

Name: CS, ID: 11

Department 2:

Name: IT, ID: 11

HOD Details ....

CS HOD Name: Mr. Holding, Id: 10

IT HOD Name: Mr. Bewon, Id: 11

<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>

In the above example, we have created the lists which consist of the employee and department details
and printed the corresponding details. Observe the above code to understand the concept of the list
better.

List indexing and splitting


The indexing is processed in the same way as it happens with the strings. The elements of
the list can be accessed by using the slice operator [].

The index starts from 0 and goes to length - 1. The first element of the list is stored at the
0th index, the second element of the list is stored at the 1st index, and so on.
We can get the sub-list of the list using the following syntax.

list_varible(start:stop:step)

The start denotes the starting index position of the list.

The stop denotes the last index position of the list.

The step is used to skip the nth element within a start:stop

Consider the following example:

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

print(list[0])

print(list[1])

print(list[2])

print(list[3])

# Slicing the elements

print(list[0:6])

# By default the index value is 0 so its starts from the 0th element and go for index -1.

print(list[:])

print(list[2:5])
print(list[1:6:2])

Output:

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

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

[3, 4, 5]

[2, 4, 6]

Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative
indices are counted from the right. The last element (rightmost) of the list has the index -1; its adjacent
left element is present at the index -2 and so on until the left-most elements are encountered.

Let's have a look at the following example where we will use negative indexing to access the elements of
the list.

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

print(list[-1])

print(list[-3:])

print(list[:-1])

print(list[-3:-1])

Output:

[3, 4, 5]

[1, 2, 3, 4]

[3, 4]
As we discussed above, we can get an element by using negative indexing. In the above code, the first
print statement returned the rightmost element of the list. The second print statement returned the
sub-list, and so on.

Updating List values


Lists are the most versatile data structures in Python since they are mutable, and their
values can be updated by using the slice and assignment operator.

Python also provides append() and insert() methods, which can be used to add values to
the list.

Consider the following example to update the values inside the list.

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

print(list)

# It will assign value to the value to the second index

list[2] = 10

print(list)

# Adding multiple-element

list[1:3] = [89, 78]

print(list)

# It will add value at the end of the list

list[-1] = 25

print(list)

Output:

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

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

[1, 89, 78, 4, 5, 6]

[1, 89, 78, 4, 5, 25]

The list elements can also be deleted by using the del keyword. Python also provides us the remove()
method if we do not know which element is to be deleted from the list.
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.

Let's see how the list responds to various operators.

Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Description Example

Repetition The repetition operator enables the list L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]


elements to be repeated multiple times.

Concatenation It concatenates the list mentioned on either l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]


side of the operator.

Membership It returns true if a particular item exists in a print(2 in l1) prints True.
particular list otherwise false.

Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
4

Length It is used to get the length of the list len(l1) = 4

Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which can
be iterated as follows.

list = ["John", "David", "James", "Jonathan"]

for i in list:

# The i variable will iterate over the elements of the List and contains each element in each iteration.
print(i)

Output:

John

David

James

Jonathan

Adding elements to the list

Python provides append() function which is used to add an element to the list. However, the append()
function can only add value to the end of the list.

Consider the following example in which, we are taking the elements of the list from the user and
printing the list on the console.

#Declaring the empty list

l =[]

#Number of elements will be entered by the user

n = int(input("Enter the number of elements in the list:"))

# for loop to take the input

for i in range(0,n):

# The input is taken from the user and added to the list as the item

l.append(input("Enter the item:"))

print("printing the list items..")

# traversal loop to print the list items

for i in l:

print(i, end = " ")

Output:

Enter the number of elements in the list:5

Enter the item:25

Enter the item:46

Enter the item:12

Enter the item:75


Enter the item:42

printing the list items

25 46 12 75 42

Removing elements from the list


Python provides the remove() function which is used to remove the element from the list.
Consider the following example to understand this concept.

Example -

list = [0,1,2,3,4]

print("printing original list: ");

for i in list:

print(i,end=" ")

list.remove(2)

print("\nprinting the list after the removal of first element...")

for i in list:

print(i,end=" ")

Output:

printing original list:

01234

printing the list after the removal of first element...

0134
Python List Built-in functions
Python provides the following built-in functions, which can be used with the lists.

SN Function Description Example

1 cmp(list1, list2) It compares the elements of This method is not used in the Python 3 and
both the lists.
the above versions.

2 len(list) It is used to calculate the L1 = [1,2,3,4,5,6,7,8]


length of the list. print(len(L1))
8

3 max(list) It returns the maximum L1 = [12,34,26,48,72]


element of the list. print(max(L1))
72

4 min(list) It returns the minimum L1 = [12,34,26,48,72]


element of the list. print(min(L1))
12

5 list(seq) It converts any sequence to str = "Johnson"


the list. s = list(str)
print(type(s))
<class list>

Let's have a look at the few list examples.

Example: 1- Write the program to remove the duplicate element of the list.

list1 = [1,2,2,3,55,98,65,65,13,29]

# Declare an empty list that will store unique values

list2 = []

for i in list1:

if i not in list2:

list2.append(i)
print(list2)
Output:

[1, 2, 3, 55, 98, 65, 13, 29]

Example:2- Write a program to find the sum of the element in the list.

list1 = [3,4,5,9,10,12,24]

sum = 0

for i in list1:

sum = sum+i

print("The sum is:",sum)


Output:

The sum is: 67

Example: 3- Write the program to find the lists consist of at least one common element.

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

list2 = [7,8,9,2,10]

for x in list1:

for y in list2:

if x == y:

print("The common element is:",x)


Output:

The common element is: 2

Example

Create a List:

thislist = ["apple", "banana", "cherry"]

print(thislist)
Output

['apple', 'banana', 'cherry']


Access Items

You access the list items by referring to the index number:


Example

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]

print(thislist[1])
Output

Banana

Negative Indexing

Negative indexing means beginning 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"]

print(thislist[-1])
Output

Cherry

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

print(thislist[2:5])
Output

['cherry', 'orange', 'kiwi']

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.


By leaving out the start value, the range will start at the first item:
Example

This example returns the items from the beginning to "orange":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4])
Output

['apple', 'banana', 'cherry', 'orange']

By leaving out the end value, the range will go on to the end of the list:
Example

This example returns the items from "cherry" and to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:])
Output

['cherry', 'orange', 'kiwi', 'melon', 'mango']

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:
Example

This example returns the items from index -4 (included) to index -1 (excluded)

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[-4:-1])
Output

['orange', 'kiwi', 'melon']

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

thislist[1] = "blackcurrant"

print(thislist)
Output

['apple', 'blackcurrant', 'cherry']

Loop Through a List

You can loop through the list items by using a for loop:
Example

Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]

for x in thislist:

print(x)
Output

apple

banana

cherry

Check if Item Exists

To determine if a specified item is present in a list use the in keyword:


Example

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]

if "apple" in thislist:

print("Yes, 'apple' is in the fruits list")


Output

Yes, 'apple' is in the fruits list


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

print(len(thislist))
Output

Add 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"]

thislist.append("orange")

print(thislist)
Output

['apple', 'banana', 'cherry', 'orange']

To add an item at the specified index, use the insert() method:


Example

Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]

thislist.insert(1, "orange")

print(thislist)
Output

['apple', 'orange', 'banana', 'cherry']


Remove Item

There are several methods to remove items from a list:


Example

The remove() method removes the specified item:

thislist = ["apple", "banana", "cherry"]

thislist.remove("banana")

print(thislist)
Output

['apple', 'cherry']

Example

The pop() method removes the specified index, (or the last item if index is not specified):

thislist = ["apple", "banana", "cherry"]

thislist.pop()

print(thislist)
Output

['apple', 'banana']

Example

The del keyword removes the specified index:

thislist = ["apple", "banana", "cherry"]

del thislist[0]

print(thislist)
Output

['banana', 'cherry']
Example

The del keyword can also delete the list completely:

thislist = ["apple", "banana", "cherry"]

del thislist
Output

Traceback (most recent call last):

File "demo_list_del2.py", line 3, in <module>

print(thislist) #this will cause an error because you have succsesfully deleted "thislist".

NameError: name 'thislist' is not defined

Example

The clear() method empties the list:

thislist = ["apple", "banana", "cherry"]

thislist.clear()

print(thislist)
Output

[]

Copy a List

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made in list2.

There are ways to make a copy, one way is to use the built-in List method copy().
Example

Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]

mylist = thislist.copy()

print(mylist)
Output

['apple', 'banana', 'cherry']


Another way to make a copy is to use the built-in method list().
Example

Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]

mylist = list(thislist)

print(mylist)
Output

['apple', 'banana', 'cherry']

Join Two Lists

There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.


Example

Join two list:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

list3 = list1 + list2

print(list3)
Output

['a', 'b', 'c', 1, 2, 3]

Another way to join two lists are by appending all the items from list2 into list1, one by one:
Example

Append list2 into list1:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

for x in list2:

list1.append(x)

print(list1)
Output

['a', 'b', 'c', 1, 2, 3]

Or you can use the extend() method, which purpose is to add elements from one list to another list:
Example

Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b", "c"]

list2 = [1, 2, 3]

list1.extend(list2)

print(list1)
Output

['a', 'b', 'c', 1, 2, 3]

The list() Constructor

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


Example

Using the list() constructor to make a List:

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

print(thislist)
Output

['apple', 'banana', 'cherry']

You might also like