# List and Tuple in python

For storing collection of data there are 4 data types available in python

• List
• Tuple
• Set
• Dictionary

## List

A dynamic container or array which can store set of values of any type like integer, string, bool etc. List items are ordered, changeable, and also allow duplicate value. Each item in list have a ordered index which start from 0. Lists are dynamic mean no need to set the size of list or type of list it size can be increase dynamically.

Example:

``the_list = ['Apple', "orange", 20, 20.5]``

List value can be accessed by its index like

• the_list[0] will return Apple
• the_list[1] will return orange

A list can also be slice by using colon in square brackets like

• the_list[0:2] will return a list of first 2 items [“Apple”, “Orange”]
• the_list[-2:] will return a list of last 2 items [20, 20.5]

### Functions of list

Some important functions of list are given below

Consider the following list

``````list1 = [1, 8, 3, 4, 10]

list1.sort() #will sort a list
print(list1)

list1.reverse() #will reverse a given list
print(list1)

list1.append(40) #will append 40 at the end of list
print(list1)

list1.insert(3, 25) #will add value 25 at index 3
print(list1)

list1.pop(2) #will del element at index
list1.remove(25) #will remove 21 from the list if available in list
len(list1) #will return the length of list``````

### list() Constructor

A list can also created by list() constructor like

• the_list = list() # An empty list
• the_list = list(“Apple”, “Banana”, “orange”) #List with 3 elements

## Tuple

Tuple is also used to store a collection of items in ordered way and it can also be accessed by item index but the only difference between list and tuple is tuple items can not be changed once they defined.

### How to create

We can create tuple in different ways but the simplest way to create a tuple is use round brackets. Like

``the_tuple = ("Apple", "Orange", "Banana")``

we can also create a tuple by tuple() constructor like

``the_tuple = tuple()``

We can use all data types items in tuple also list data type like

``the_tuple = ("Apple", "Orange", 20, [1, 3])``

tuple also allowed duplicate values.

### Tuple with single item

If we want to define a tuple with single item it is a little much tricky, there should be a trailing comma with single item like

``the_tuple = ("Apple", )``

### Functions of tuple

• the_tuple.count(“Apple”) will count the “Apple” in a tuple
• the_tuple.index(“Apple”) will return the index of “Apple”