Python: List Vs Tuple

 The aim of this tutorial is to state the differences between lists and tuples and how to manage these two data structures.

Lists and Tuples are types of data structures that hold one or more than one objects or items in a predefined order. We can contain objects of any data type in a list or tuple, including the null data type defined by the 'None' keyword.

What is a List?

In other programming languages, list objects are declared similarly to arrays. Lists don't have to be homogeneous all the time, so they can simultaneously store items of different data types. This makes lists the most useful tool. The list is a kind of container data structure of Python that is used to hold numerous pieces of data simultaneously. Lists are helpful when we need to iterate over some elements and keep hold of the items.

What is a Tuple?

A tuple is another data structure to store the collection of items of many data types, but unlike mutable lists, tuples are immutable. A tuple, in another words, is a collection of items separated by commas. Because of its static structure, the tuple is more efficient than the list.

Differences between Lists and Tuples

In most cases, lists and tuples are equivalent. However, there are some important differences to be explored here.

Syntax Differences

The syntax of a list differs from that of tuple. Items of a tuple are enclosed by parantheses or curved brackets (), whereas items of a list are enclosed by square brackets [].

Example Code:

#Python program to show the differences between creating a list and a tuple
list_=[5, 3, 7, 9, 1]
tuple_=(2, 4, 6, 8, 12)

print("List is:", list_)
print("Tuple is:", tuple_)

Output:

List is: [5, 3, 7, 9, 1]
Tuple is: (2, 4, 6, 8, 12)

In above example, we have declared both list and tuple. Both have certain numbers of entegers, but list is enclosed by [] (square brackets) whereas tuple is enclosed by () (curly brackets). We can find out the data type whether it is list or tuple, by type() method.

Example Code:

#Python program to show the data type of a data structure
list_=[5, 3, 7, 9, 1]
tuple_=(2, 4, 6, 8, 12)

print(type(list_))
print(type(tuple_))

Output:

<class 'List'>
<class 'Tuple'>

Mutable Vs. Imutable (List Vs. Tuple)
An important difference between a list and a tuple is that a List is mutable whereas a Tuple is immutable. Means, a List's items  can be easily modified or changed whereas a Tuple's items cannot be modified or changed.

As a List is a mutable data type so it cannot be employed as key of dictionary. Because a key of a Python dictionary is an immutable object. So Tuples can be used as keys to a dictionary, if required.

The following code example will show the mutable and immutable nature of a list and a tuple:

#creating a list and a tuple
list_=[5, 3, 7, 9, 1]
tuple_=(2, 4, 6, 8, 12)

#modifying the last integer in both data types
print(list_)
list_[4]=100
print(list_)

print(tuple_)
try:
    tuple_[4]=20
    print(tuple_)
except TypeError:
 print("Tuples cannot be modified because they are immutable")

Output:

[5, 3, 7, 9, 1]
[5, 3, 7, 9, 100]
(2, 4, 6, 8, 12)
Tuples cannot be modified because they are immutable.

Here, we can easily notice that when we tried to change the last element of a list, it is changed (from 1 to 100), but when we tried to change the last element of a tuple (from 12 to 20) in a try block, it raised an error. We got output from except block. This is because tuples are immutable.

Size difference:
Since tuples are immutable, Python allocates bigger chunks of memory with minimal overhead. Python on the contrary, allots smaller memory chunks for lists. The tuple would therefore have less memory than the list. If we have a huge number of items, this makes tuples a little more memory efficient than lists.
In the following example, we will create a list and a tuple with identical items and compare their sizes:

#code to show differences in size of a list and a tuple
#creating a list and a tuple
list_=["Tuple", "List", "Python", "Differences"]
tuple_=("Tuple", "List", "Python", "Differences")

#printing sizes
print("Size of Tuple:", tuple_.__sizeof__())
print("Size of List:", list_.__sizeof__())

Output:

Size of Tuple: 56
Size of List: 72

Available Functions:
Tuples have fewer built in functions than lists. We may leverage the in-built function dir([object) to access all the corresponding methods for the list and tuple.

Examples
To print directory of a list
list_=["Tuple", "List", "Python", "Differences"]
#printing directory of list
dir(list_)

Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

To print directory of a tuple:

tuple_=["Tuple", "List", "Python", "Differences"]
#printing directory of list
print(dir(tuple_),end=",")

Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Tuples and Lists: Key similarities
  • They both hold collection of items and are heterogeneous data types, means they can contain multiple data types simultaneously.
  • They're both ordered, which implies the items or objects are maintained in the same order as they were placed until changed manually.
  • Because they're both sequential data structures, we can iterate through the objects they hold, hence they are iterables.
  • An integer index, enclosed in square brackets[index], can be used to access objects of both data types.

Python: Tuple

 In Python, a tuple is one of the data types that holds the sequence of items. All the items or elements are separated from each other by comma (,) and enclosed in paranthesis(). Although the parentheses are not required, they are recommended.

Features of Python Tuple:

  • Tuples are an immutable data type, meaning their elements cannot be changed after they are formed.
  • Each element in a tuple has a specific order, that will be never changed because tuples are ordered sequences.
Forming a Tuple:
Any number of items, including those with various data types dictionary, string, float, list etc can be contained in a tuple.

Code:

#Python program to show how to create a tuple
#Creating an empty tuple
empty_tuple=()
print("empty tuple:", empty_tuple)

#Creating tuple having integers
int_tuple=(2, 4, 6, 8, 10)
print("tuple with integers:", int_tuple)

#Creating a tuple having objects of different data types
mixed_tuple=(2, "Python", 6.8, 10)
print("tuple with different data types:", mixed_tuple)

#Creating a nested tuple 
nested_tuple=("Python", {6:8, 9:8, 5:2}, (3, 5, 7))
print("A nested tuple:", nested_tuple)


Output:

empty tuple: ()
tuple with integers: (2, 4, 6, 8, 10)
tuple with different data types: (2, "Python", 6.8, 10)
A nested tuple: 
("Python", {6:8, 9:8, 5:2}, (3, 5, 7))

Parentheses are not necessary for the construction of multiples. This is known as tripple pressing.

Code:

#Python program to create a tuple without using parentheses
#Creating the tuple
tuple_=4.2, "Python", ["Lists", "tuples"]
#displaying the tuple 
print(tuple_)
#checking the data type of object tuple_
print(type(tuple_))
#trying to modify the tuple_
try:
    tuple[1]=4.5
except:
    print(TypeError)


Output:

(4.2, "Python", ["Lists", "tuples"])
<class 'tuple'>
<class 'TypeError'>
 Here, some elements are not in brackets, however elements must be seperated by comma(,) to recognize the tuple.

We can verify the above statement by following code: 

Code:

#Python program to show how to create a tuple having single element
#when we don't use comma(,)
tuple_single=("Python")
print(type(tuple_single))

#using of comma(,)
tuple_single=("Python",)
print(type(tuple_single))

#missing of brackets
tuple_single="Python",
print(type(tuple_single))


Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

It is proved by above code that bracket is not but comma(,) is necessary to make a tuple.

Accessing Tuple Elements
A tuple's object can be accessed in a variety of ways:

1. Indexing:
We can use the index operator [] to access an object in a tuple, where the index starts at zero (0). If a tuple has five elements, the index will denote these 0 to 4 respectively. If we try to get the element that is outside the scope like index[5], we get an error message. 
Let's see the above statements in programming:

Code:

#Python program to show indexing.
tup=(5, 7, 6, 8, 9)
print(tup[0])
print(tup[1])
print(tup[2])
print(tup[4])
print(tup[5])


Output:

5
7
6
9
IndexError: tuple index out of range

We cannot provide an index of a floating data type. It only works with integers or slices. If we provide a floating index, the result will be TypeError.

Code:

#Python program to show indexing with float.
tup=(5, 7, 6, 8, 9)
print(tup[1.0])


Output:

IndexError: tuple indices must be integers or slices, not float.

Nested Tuple:
In nested tuple the indexing is done by two numbers, First number indicates the tuples, it also starts from zero(0) and second number indicates the element of that particular tuple, it also starts from zero(0).
Let's understand it by codes:

Code:

#Python program to show indexing in nested tuples.
tup_nested=("Pythpn", [4, 3, 2, 1], (5, 7, 6, 8, 9))
print(tup_nested[0][2])
print(tup_nested[1][0])
print(tup_nested[2][4])


Output:

t
4
9

Negative Indexing:
Python tuple supports negative indexing too. It starts from -1 and it indicates the rightmost element of the tuple. -2 indicates the second last and so on.
Let's try it 

Code:

#Python program to show negative indexing in  tuple.
tup_negInd=("orange", "apple", "banana", "mango")
print(tup_negInd[-1])
print(tup_negInd[-3])
print(tup_negInd[-4:-1])


Output:

mango
apple
('orange', 'apple', 'banana')

Slicing:
Slicing is a comman practice in Python and the most comman way for programmers to deal with practical issues.By slicing in Python tuple, we can get only some sequential elements or a part of the tuple which is required.
Let's understand it by codes:

Code:

#Python program to show slicing in Python tuples.
tup_slicing=("orange", "apple", "banana", "mango", "lemon", "papaya")
#to see only first four elements
print(tup_slicing[0:4])
#to see the elements between 2nd and 5th elements
print(tup_slicing[2:5])
#to see the entire tuple
print(tup_slicing[:])


Output:

('orange', 'apple', 'banana', 'mango')
('banana', 'mango', 'lemon')
('orange', 'apple', 'banana', 'mango', 'lemon', 'papaya')

Deleting a Tuple:
As discussed earlier, a tuple's element cannot be modified or removed but we can remove entire tuple by del keyword.

Code:

#Python program to delete a Python tuple.
tup_=("orange", "apple", "banana", "mango", "lemon", "papaya")
print(tup_)
# try to delete only one element
print(del[2])
#to delete entire tuple
del(tup_)
print(tup_)


Output:

('orange', 'apple', 'banana', 'mango', 'lemon', 'papaya')
SyntaxError: invalid syntax
name 'tup_' is not defined

In above output, we tried to delete the 2nd element of the tuple by syntax del[2], but it is recognised as invalid syntax by Python. whereas when we deleted the entire tuple by syntax del(tup_), the tuple is deleted and then we tried to print the tuple, but now it doesnot exist, so the message appears name'tup_' is not defined.

Repeat Tuples in Python:
We can repeat the elements of the  tuple as following example:

Code:

#Python program to show repetition in Python
tup_=("orange", "apple")
print("The original tuple is :", tup_)
# repeting the tuple's element
tup_= tup_*3
print("New tuple is :", tup_)


Output:

The original tuple is : ('orange', 'apple')
New tuple is : ('orange', 'apple', 'orange', 'apple', 'orange', 'apple')

Tuple Methods:
Count() and Indez() methods in Python:
We all know Python tuple is a collection of immutable objects. However there are some ways to work with tuples in Python. These are count() and Index () methods, which are explained here by some examples.

Count() method:

The times the predetermined component happens in the tuple is returned by the count() capability of the Tuple.

Code:

#creating tuples
tup_1=(0, 1, 4, 3, 2, 3, 2, 4, 1, 3, 4, 2)
tup_2=("orange", "apple", "banana", "apple", "orange", "papaya")
# counting the appearance of 2 in tup_1
res= tup_1.count(2)
print("Count of 2 in tup_1:", res)
# counting the appearance of orange in tup_2
res= tup_2.count('orange')
print("Count of orange in tup_2:", res)


Output:

Count of 2 in tup_1: 3
Count of orange in tup_2: 2

Index() Method:
The index() function returns the first instance of the requested element from the Tuple.

Parameters: 
  • The thing that must be looked for.
  • Start: (Optional) the index is used to begin the final (optional) search: the most recent index from which the search is carried out.
  • Index Method
Code:

#creating tuples
tup_1=(0, 1, 4, 3, 2, 3, 2, 4, 1, 3, 4, 2)
#getting the index of 3
res =  tup_1.index(3)
print("first occurance of 3 is:", res)
# getting the index of 3 after 4th index
res= tup_1.index(3, 4)
print("first occurance of 3 after 4th index is:", res)

Output:

first occurance of 3 is: 3
first occurance of 3 after 4th index is: 5

Tuple Membership Test:
Utilizing the watchword, we can decide whether a thing is available in the given Tuple.

Code:

#Python progrm to show how to perform membership test for tuples.
#creating a tuple
tup_=("orange", "apple", "banana", "apple", "orange", "papaya")
#in operator
print('apple' in tup_)
print('tomato' in tup_)
#not in operator
print('potato' not in tup_)
print('orange' not in tup_)

Output:

True
False
True
False

Iterating Through a Tuple

A for loop can be used to iterate through each tuple element.

Code:

#Python progrm to show how to iterate over tuple elements
#creating a tuple
tup_=("orange", "apple", "banana", "apple", "orange", "papaya")
#iterating over tuple elements using a for loop
for item in tup_:
    print(item)

Output:

orange
apple
banana
apple
orange
papaya

Changing a Tuple:
Tuples, instead of records, are permanent articles.
This suggests that once the elements of a Tuple have been defined, we cannot change them. However the nested elements can be altered if the element itself is a chargeable data type like a list.

Multiple values can be assigned to a Tuple through reassignment.

Code:

#Python progrm to show that Python tuples are immutable objects.
#creating a tuple
tup_=("orange", "apple", "banana", "apple", [1, 2, 3, 4])
#trying to change the element at index 2
try:
    tup_[2] = "items"
    print(tup_)
except Exception as e:
    print(e)
#but inside a tuple, we can change elements of a mutable object
tup_[-1][2] = 10
print(tup_)
#changing the whole tuple
tup_=(
"orange", "apple")
print(tup_)

Output:

'tuple' object doesn't support item assignment
('orange', 'apple', 'banana', 'apple', [1, 2, 3, 4])
('orange', 'apple')

The + operator can be used to combine multiple tuples into one. This phenomenon is known as concatenation.
We can also repeat the elements of a tuple a predetermined number of times by using the * operator. This is already demonstrated above.
The aftereffects of tasks + and * are new tuples.

Code:

#Python progrm to show how to concatenate tuples.
#creating a tuple
tup_=("orange", "apple", "banana", "apple")
#adding a tuple to the tup_
print(tup_ + (1, 2, 3))

Output:

('orange', 'apple', 'banana', 'apple', 1, 2, 3)

Tuples have the following advantages over lists:
  • Tuples take less time than lists do.
  • Due to tuples, the code is protected from accidental modifications. It is desirable to store non-changing information in "tuples" instead of "records" if a program expects it.
  • A tuple can be used as a dictionary key if it contains immutable values like strings, numbers, or another tuple. "Lists" cannot be utilized as dictionary keys because they are mutable. 

Python: List

 In Python, a list  is one of the data types hold the sequence of data. In other words a list is a collection of different values or items. In Python the lists are mutable, means we can change the elements of the list after forming it. The comma(,) is used as a separator of each item or element  and square bracket [] is used to hold all the elements of one list separated by comma.

Although six Python data types can hold the sequence of items, but the list is most common and reliable among all. Lists written in Python are identical to array list in Java or vector in c++.

List declaration codes:

#a simple list
list1 = [1, 2, "Python", "Program", 98.6]
list2 = ["mango", "guava", "papaya", "litchi"]

#printing the list
print(list1)
print(list2)

#printing the type of list
print(type(list1))
print(type(list2))


Output:

[1, 2, 'Python', 'Program', 98.6]
['mango', 'guava', 'papaya', 'litchi']
<class 'list'>
<class 'list'>


Characteristics of Lists:
The characteristics of the list are as follows:
  • The lists are in order.
  • The list element can be accessed via the index.
  • The list is a mutable type.
  • The number of various elements can be stored in a list.
  • The rundowns are changeable sorts.
Ordered List Checking :

#example1
list1 = [1, 2, "Python", "Program", 98.6]
list2 = [1, 2, 98.6, "Python", "Program"]

list1==list2
#example 2
list3 = [1, 2, "Python", "Program", 98.6]
list4 = [1, 2, "Python", "Program", 98.6]

list3==list4


Output:

False
True

In above examples, the elements of both the lists are same but order is different in example 1, so it is showing 'False'. But when list elements and order both are same in example 2, it is showing 'True'.
Records forever protect the component's structure. Because of this, it is an arranged collection of things, Let's take a closer look at the list example:

#list example in detail
emp = ["Tim", 102, "USA"]
Dep1=["Acc", 10]
Dep2=["IT", 11]
HOD_Acc=[10, "Mr. Wilson"]
HOD_IT=[11, "Mr. Samson"]
print("printing employee data......")
print("Name:%s, ID:%d, Country:%s"%(emp[0], emp[1], emp[2]))
print("printing departments.....")
print("Department 1:\n, Name: %s, ID: %d\n Department 2:\n, Name: %s, ID: %d"%(Dep1[0], Dep1[1], Dep2[0], Dep2[1]))
print("HOD details.....")
print("Acc HOD Name: %s, ID: %d"%(HOD_Acc[1], HOD_Acc[0]))
print("IT  HOD Name: %s, ID: %d"%(HOD_IT[1], HOD_IT[0]))
print(type(emp), type(Dep1), type(Dep2), type(HOD_Acc), type(HOD_IT))

Output:

printing employee data......
Name: Tim, ID: 102, Country: USA
printing departments.....
Department 1:
Name: Acc, ID: 10
Department 2:
Name: IT, ID: 11
printing HOD details.....
Acc HOD Name: Mr. Wilson,  ID: 10
IT HOD Name: Mr. Samson,  ID: 11
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>                               

Here we have printed the employee and department specific details from list that we had created. 

List Indexing and Splitting:

The indexing procedure in list is similar to that as in string processing. The slice operator [] can be used to hold the list components.
The index ranges from 0. The 0th index is where the index first element is stored, the 1st element is where the index second element is stored and so on..

                                            List = [0, 1, 2, 3, 4, 5]


0

1

2

3

4

5


List[0]=0                                    List[0:]=[0, 1, 2, 3, 4, 5]    
List[1]=1                                    List[:]=[0, 1, 2, 3, 4, 5]   
List[2]=2                                    List[2:4]=[2, 3]
List[3]=3                                    List[1:3]=[1, 2] 
List[4]=4                                    List[:4]=[0, 1, 2, 3] 
List[5]=5 

We can get the sub list of the list using the following syntax .
list_variable=(start:stop:step)
  • Here, the start indicates the beginning record position of the rundown.
  • The stop indicates the last record position of the rundown.
  • Within a start, the step is used to skip the nth element: stop.

The start parameter is the initial index, the step is the ending index, and the value of the end parameter is the number of elements that are "stepped" through. The default value for the step is one without a specific value. Inside the resultant Sub List, the same with record start would ber available, yet the one with the file finish will not, The first element in a list appears to have an index of zero.

Consider the following example:

list=[1, 2, 3, 4, 5, 6, 7]
print(list[0])
print(list[1])
print(list[2])
print(list[3])
print(list[:])
print(list[0:6])
print(list[2:5])
print(list[1:6:2])

Output:

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

In opposite to other programming language, Python lets you use negative indexing as well. The negative indices are counted from right. Negative indexing starts from -1 and it indicated the rightmost element of the list, -2 indicates the second last, -3 for third last and this pattern continues untill the last element in the  leftmost side arrives. 

(forward direction)

        0              1              2               3               4              5

0

1

2

3

4

5

      -6              -5             -4            -3              -2             -1

                                                                                             (backward direction)    
Lets have a look at the followimg example, here we'll use negative indexing to the elements of the list.  
Negative indexing example:   

list=[1, 2, 3, 4, 5]
print(list[-1])
print(list[-3:])
print(list[:-1])
print(list[-3:-1])


Output:

5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
                                                                                                                                                       Updating List Values:
Due to their mutability and the slice and assignment operator's ability to update their values, lists are Python's most adaptable data structure. Python's append() and insert() methods can also add values to a list.
Consider the following example to upodate the values inside the list.

Code:

list=[1, 2, 3, 4, 5]
print(list)
#now assign new value to the second index
list[2]=10
print(list)
#adding multiple element
list[1:3]=[89,78]
print(list)
#adding value at the end of the list
list[-1]=25
print(list)

                                                                                                                                            
Output:

[1, 2, 3, 4, 5]
[1, 2, 10, 4, 5]
[1, 89, 78, 4, 5]
[1, 89, 78, 4, 25]

Python List Operations
The concatenation (+) and the repetition (*) operators work in the same way as they were working with the strings. The different operators of list are:

  1. Repetition
  2. Concatenation
  3. Length
  4. Iteration
  5. Membership
Let's see how the list responds to various operators.
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on different occasions.
Code:

#declaring the list
list=[1, 2, 3, 4, 5]
print(list)
#repetition of list
r = list*2
print(r)

                                                                                                                                            
Output:

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


2. Concatenation:
It concatenates the list mentioned mentioned on either side of the operator.

Code:

#declaring the lists
list1=[1, 2, 3, 4, 5]
list2=[6, 7, 8, 9, 10]
#concatenating the lists
print(list1+list2)
                                                                                                                                   
Output:

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


3. Length:
It is used to get the length of the list.
Code:

#declaring the list
list1=[10, 12, 14, 16, 18, 20, 22, 24]
#size of the lists
len(list1)
                                                                                                                                   
Output:

8

4. Iteration:
The for loop is used to iterate over the list elements.

Code:

#declaring the list
list1=[10, 12, 14, 16, 18, 20, 22, 24]
#iterating
for i in list1:
    print (i)
                                                                                                                                   
Output:

10
12
14
16
18
20
22
24

5. Membership:
It returns true if a particular item presents in a particular list otherwise false.

Code:

#declaring the list
list1=[10, 12, 14, 16, 18, 20, 22, 24]
#membership of the list
#returns true if value exists in list otherwise false.
print(14 in list1)
print(15 in list1)
print(100 in list1)
print(22 in list1)
                                                                                                                                   
Output:

True
False
False
True

Adding Elements to the List:
The append() function in Python can add a new item to the list. In any case, the annex() capability can enhance the finish of the rundown.
Consider the following model, here we take the components of the rundown from the client and print the rundown on the control center.

Code:

#declaring the empty list
list=[]
#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 items
    list.append(input("Enter the item:"))
print("printing the list items")
#traversal loop to print the list items
for i in list:
    print(i, end=" ")
                                                                                                                                   
Output:

Enter the number of elements in the list:10
Enter the item: 32
Enter the item: 88
Enter the item: 46
Enter the item: 17
Enter the item: 42
Enter the item: 29
Enter the item: 58
Enter the item: 61
Enter the item: 45
Enter the item: 73
printing the list items
32  88  46  17  42  29  58  61  45  73


Removing Elements from the List
The remove() function in Python can remove an element from the list. Let's implement the remove() function in Python code and check the output.

Code:

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 removal of first element...")
for i in  list:
    print(i,end"=")
print("printing the list items")
#traversal loop to print the list items
for i in list:
    print(i, end=" ")

Output:

printing original list:
0, 1, 2, 3, 4
printing the list after removal of first element...
0, 1, 3, 4

Python List Built-In-Functions:
Python provides the following built in functions which can be used with the list.
  • len()
  • max()
  • min()
len(): It is used to calculate the length of the list.

Code:

list=[0, 1, 2, 3, 4]
len(list)

Output:

5

max(): It returns the maximum element of the list.

Code:

list=[0, 1, 2, 3, 4]
print(max(list))

Output:

4

min(): It returns the minimum element of the list.

Code:

list=[0, 1, 2, 3, 4]
print(min(list))

Output:

0

Question: Write a Python program to find out a common element between two lists.

Code:

list1=[0, 1, 2, 3, 4]
list2=[8, 7, 6, 5, 4]
for x in list1:
    for y in list2:
        if x==y:
            print("The common element is",x)

Output:

The common element is 4



                                                                                                                                   
                                                        

Python: Strings

 In this tutorial, we will discuss one of  the most popular data type in Python, i.e. string. Python string is the collection of the characters surrounded by single quotes, double quotes or triple quotes. The computer doesn't understand the characters internally, it stores manipulated character as the combination of 0's and1's.

Each character is encoded in the ASCII or Unicode character. So Python strings are also called the collection of Unicode characters.

Syntax:

str = "Hi Python!"

We can also check the type of the string variable using a Python script.

s = "Hi Python!"
print(type(s))

Output:
<class 'str'>

In Python strings are treated as the sequence of characters, that means Python doesn't support the character data type, instead a single character written as "A" is treated as the string of length 1.

Creating String in Python
We can create a string by enclosing the characters in single quotes or double quotes. We can also use triple quotes to represent multiline strings called docstrings.

#Single quotes string
s1 = 'Learn Python'
#Double quotes string
s2 = "Learn Python"
#Triple quotes string
s3 = '''Used to 
write
multiline string'''

print(s1);print(s2);print(s3)

Output:
Learn Python
Learn Python
Used to 
write
multiline string

String indexing and splitting
Like other programming languages, the indexing of the Python string starts from'0'.

For example:

 STRING:            P        Y      T       H      O     N

INDEXING:                    0              1           2             3           4          5       

In above example string PYTHON is indexed as above. 
Here, letters are indexed as:
str[0]='P'
str[1]='Y'
str[2]='T'
str[3]='H'
str[4]='O'
str[5]='N'

Check the above example in Python coding:
s = "Python"
print(s[0]);print(s[1]);print(s[2]);print(s[3]);print(s[4]);print(s[5])

Output:
P
y
t
h
o
n


As shown in above example, the slice operator[] is used to access the individual character of a string. However, we can use (:) colon operator to access the substring from the given string.

For example:

 STRING:            P        Y      T       H      O     N

INDEXING:                     0              1            2            3           4          5       

str[0]='P'
str[1]='Y'
str[2]='T'
str[3]='H'
str[4]='O'
str[5]='N'

str[:]='PYTHON'
str[0:]='PYTHON'
str[1:4]='YTH'
str[0:2]='PY'

Let's check the code
s = "Python"
print(s[:]);print(s[1:3]);print(s[0:2]);print(s[0:]);print(s[4:5]);print(s[:5])

Output:
Python
yt
Py 
Python
0
Pytho

We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as -1, the second rightmost character is indicated as -2, third rightmost character as -3 and so on.

Consider the following image:

 STRING:            P       Y      T       H      O     N

INDEXING:                   -6        -5        -4            -3          -2         -1

str[-1]='N'
str[-2]='O'
str[-3]='H'
str[-4]='T'
str[-5]='Y'
str[-6]='P'

str[-3:-1]='HO'
str[-4:-1]='THO'
str[-5:-3]='YT'
str[0:-2]='PYTH'

Let's check the code
s = "Python"
print(s[-1]);print(s[-2]);print(s[-3]);print(s[0:-2]);print(s[-4:-1]);print(s[-5:-3])

Output:
n
o

Pyth
tho
yt


Reassigning Strings: Updating the content of the string is as easy as assigning it to a new string. But a string can only be replaced with new string since its content can't be replaced partially. Strings are immutable in Python.

For example

s = "HELLO"
print(s)
s = "hello"
print(s)

Output:
HELLO
hello

Deleting the string: As we know that the strings are immutable. We cannot delete or remove the characters from the string. But we can delete the entire string by del keyword.

For example

s = "HELLO"
del s
print(s)

Output:
NameError: name 's' is not defined

String Operators:

Operators

Description

+

It is known as concatenation operator, used to join the strings.

*

It is known as the repetition operator and used to concatenate the multiple copies of the same string.

[]

It is known as slice operator, used to access the sub-strings of a particular string.

[:]

It is known as range slice-operator, used to access the characters from the specified range.

In

It is known as membership operator. It returns if a particular sub-string is present in the specified string.

not in

It is also known as membership operator and is just reverse to in operator. It returns ‘true’ if a particular sub-string is not present in the specified string.

r/R

It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual meaning of escape characters such as “C://python”. To define any string to a raw string, the character r or R is followed by the string.

%

It is used to perform string formatting. It makes use of the format specifiers used in C programming like %d or %f to map their values in Python. We will discuss how formatting is done in Python.


For example

s = "learn"
s1 = " python"
print(s+s1) #concatenate the strings s and s1
print(s1*3) # repeats the string s1 3 times
print(s[4]) #print 4th character of string s
print(s[1:5]) #print the characters of string s after 1st and till 5th character
print('o' in s) # if 'o' is present in s, will print true otherwise false.
print('o' in s1) # if 'o' is present in s1, will print true otherwise false.
print('e' not in s) # if 'e' is not present in s, will print true otherwise false.
print(r'C://python') #print ://python as it is.
print("the string str: %s"%(s)) #print the sring str: learn.

Output:
learn python
python python python
n
earn
false
true
false
C://python
the string str: learn

Python String Formatting:
Escape Sequence
Let's suppose we need to write the text as -They said, "What's your occupation?" - the given statement can be written in single quote or double quote but it will raise the SyntaxError as it contains both single and double quotes.

For example

s = "They said, "What's your occupation?""
print(s)

Output:
SyntaxError: invalid syntax

However we can use triple codes to accomplish this problem but Python provides the escape sequence.
The backslash (\) symbol denotes the escape sequence. The backslash can be followed by a special character and it interpreted differently. The single quotes inside the string must be escaped. We can use the same as in double quotes also.

For example

#using triple quotes
print('''They said, "What's your occupation?"''')

#escaping single quotes
print('They said, "What\'s your occupation?"')

#escaping double quotes
print("They said, \"What's your occupation?\"")

Output:
They said, "What's your occupation?"

They said, "What's your occupation?"

They said, "What's your occupation?"

The list of an escape sequence is given below:

Sr.

Escape Sequence

Description

Example

Output

1.

\newline

It ignores the new line

print(“Python1 \

Python2 \

Python3”)

Python1 Python2 Python3

2.

\\

Backslash

print(“\\”)

\

3.

\’

Single Quotes

print('\'')

 

4.

\\”

Double Quotes

print("\"")

 

5.

\a

ASCII Bell

print(“\a”)

 

6.

\b

ASCII Backspace

print(“Hello \b world”)

Hello world

7.

\f

ASCII Formfeed

print(“Hello \f world!”)

Hello world!

8.

\n

ASCII Linefeed

print(“Hello \n world!”)

Hello

   world!

9.

\r

ASCII Carriege Return(CR)

print(“Hello \r world!”)

world!

10.

\t

ASCII Horizontal Tab

print(“Hello \t world!”)

Hello               world!

11.

\v

ASCII Vertical Tab

print(“Hello \v world!”)

Hello

   world!

12.

\ooo

Character with octal value

print("\110\145\154\154\157")

 

Hello

13.

\xHH

Character with hex value

print("\x48\x65\x6c\x6c\x6f")

 

Hello

Python: Functions