3️⃣ Sequential
There are two sequential data types present in python which stores items in sequential manner.
1) List
2) Tuple
Lets understand them one by one.
👉🏻1) List
Lists are used to store multiple items in a single variable.
Lists are created using square brackets [ ].
List items are ordered, changeable (mutable) & allow duplicate values.
List items can be of any data types like : str, int, boolean, float.
Nested List: List can contains another lists inside
💻 Example:
1 2 3 | thislist = ["apple", "banana", "cherry"]
mylist = ["Sam", 12, 'good', 5.2, '60Kg']
nested_list = [[1,2,3], [2,3,4], [3,2,1], [2,2,0]]
|
How to define blank list ? We can define empty list using two ways
using builtin function: list()
using symbol: []
💻 Example:
1 2 3 4 | mylist = []
mylist2 = list()
print('The value of mylist:', mylist)
print('The value of mylist2:', mylist2)
|
✅ Output:
The value of mylist: []
The value of mylist2: []
List Slicing
We can access elements of list and slice list by providing indices.
1st list element can be accessed using index 0, 2nd element using index 1 and so on …
We can access all elements of list by just providing ‘:’ to the list brackets [ ].
Last element of list can be accessed using index -1 , 2nd last element using index -2 and so on …
Lets follow some examples of list slicing :
💻 Example:
1 2 3 4 5 6 7 8 | division_list = ['Div-A','Div-B','Div-C','Div-D','Div-E','Div-F']
print(division_list[:])
print(division_list[0])
print(division_list[3:])
print(division_list[2:5])
print(division_list[-1])
print(division_list[-3:])
print(division_list[-4:-1])
|
✅ Output:
['Div-A', 'Div-B', 'Div-C', 'Div-D', 'Div-E', 'Div-F']
Div-A
['Div-D', 'Div-E', 'Div-F']
['Div-C', 'Div-D', 'Div-E']
Div-F
['Div-D', 'Div-E', 'Div-F']
['Div-C', 'Div-D', 'Div-E']
Reverse list: We can simply reverse list by providing negative index as below.
💻 Example:
1 2 | division_list = ['Div-A','Div-B','Div-C','Div-D','Div-E','Div-F']
print(division_list[::-1])
|
✅ Output:
['Div-F', 'Div-E', 'Div-D', 'Div-C', 'Div-B', 'Div-A']
List Methods
List methods are predefined functions to modify the list or to get required information about the list.
len(): This method is used to findout length of list i.e number of elements present in list.
💻 Example:
1 2 3 4 | thislist = ["apple", "banana", "cherry"]
print(len(thislist))
nested_list = [[1,2,3], [2,3,4], [3,2,1], [2,2]]
print(len(nested_list))
|
✅ Output:
3
4
insert(): It inserts a new list item at perticular position or index of a list.
💻 Example:
1 2 | thislist.insert(2, "watermelon")
print(thislist)
|
✅ Output:
["apple", "banana","watermelon", "cherry"]
append(): This method adds items at the end of the list.
💻 Example:
1 2 | thislist.append("orange")
print(thislist)
|
✅ Output:
["apple", "banana", "watermelon", "cherry", "orange"]
extend (): Use extend() method to append elements from another list to the current list. We can add any iterable object (tuples, sets, dictionaries etc.)
💻 Example:
1 2 3 4 | thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
|
✅ Output:
['apple', 'banana', 'cherry', 'mango', 'pineapple','papaya']
.remove(): This method removes the specified items from the list.
💻 Example:
1 2 3 | thislist=["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
|
✅ Output:
["apple", "cherry"]
.pop(): This method accepts the index of item and removes that item present at specified index. If we don’t specify the index, the pop() method removes the last item of the list.
💻 Example:
1 2 3 | thislist=["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
|
✅ Output:
["apple "cherry"]
del: This keyword removes item present at specified index. It can also be used to delete list completely from memory.
💻 Example:
1 2 3 4 5 | thislist=["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
del thislist
print(thislist)
|
✅ Output:
['banana', 'cherry']
NameError: name 'thislist' is not defined
.clear(): This method empties the list. The list still remains in memory, but it has no content.
💻 Example:
1 2 3 | thislist=["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
|
✅ Output:
[]
.sort():
List objects have a sort() method that will sort the list alphabetically or in ascending order by default.
It accepts keyword argument reverse = True to sort the list in descending order.
The sort() method is case sensitive by default, resulting in all capital letters being sorted before lower case letters.
💻 Example:
1 2 3 4 5 6 | thislist=["orange","mango", "kiwi"]
thislist.sort()
print(thislist)
thislist=["orange" "mango", "kiwi"]
thislist.sort(reverse=True)
print(thislist)
|
✅ Output:
['kiwi','mango','orange']
['orange','mango','kiwi']
.reverse(): This method reverses the current sorting order of the elements.
💻 Example:
1 2 3 | thislist = ["banana", "orange", "kiwi", "cherry"]
thislist.reverse()
print(thislist)
|
✅ Output:
['cherry','kiwi','orange','banana']
.copy():
We 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 list 2.
This method copies content in first list to other, so that it will be independent list from which it has been copied.
💻 Example:
1 2 3 | mylist = ["abc", "xyz", "pqr"]
res=mylist.copy()
print(res)
|
✅ Output:
['abc', 'xyz','pqr']
List Operations
Lists support two operators:
1) Addition (+): Two lists can be added to get merged list. This will result same output as .extend() method.
💻 Example:
1 2 3 4 | mylist1 = ['one', 'two', 'three']
mylist2 = [1,2,3]
mylist3 = mylist1 + mylist2
print(mylist3)
|
✅ Output:
['one', 'two', 'three', 1, 2, 3]
2) Multiplication (*): A list can be multiplied with only integer number. The result of multiplication will be a single list, which contains the elements repeated that much number of times.
💻 Example:
1 2 3 | mylist1 = [1,2,3]
mylist2 = mylist1 * 3
print(mylist2)
|
✅ Output:
[1,2,3,1,2,3,1,2,3]
💻 Example:
1 2 3 | mylist1 = ['hello']
mylist2 = mylist1 * 3
print(mylist2)
|
✅ Output:
['hello', 'hello', 'hello']
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Lets create newlist which contains fruit names from fruits list.
syntax: [expression for item in iterable if condition == True]
💻 Example: Lets create ‘newlist’ which contains fruit names with the alphabet ‘a’ present in the name using original ‘fruits’ list using list comprehension as follows.
1 2 3 | fruits=["apple", "banana", "cherry", "kiwi","mango"]
newlist=[x for x in fruits if "a" in x]
print(newlist)
|
✅ Output:
['apple', 'banana', 'mango']
Don’t worry if you don’t get the list comprehension in detail, we are gonna learn it in detail while studying for loop concept.
Here are the quick notes on above topic:
👉🏻2) Tuple
Tuples are used to store multiple items in a single variable.
It is a collection of items which is ordered and it can contain items of different data types.
Tuples are immutable objects i.e once defined a tuple, we cannot make changes to it.
Tuples are defined using round brackets (parenthesis).
💻 Example:
1 2 | mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
|
✅ Output:
<class 'tuple'>
Single item tuple: We need to add a comma after the item to create a tuple with only one item, otherwise python will recognize it as a string.
💻 Example:
1 2 3 4 | a = ('hello')
print(type(a))
a = ('hello',)
print(type(a))
|
✅ Output:
<class 'str'>
<class 'tuple'>
Tuple methods
len(): It determine how many items a tuple contains i.e it returns length of a tuple.
💻 Example:
1 2 | mytuple = ("apple", "kiwi", "cherry")
print(len(mytuple))
|
✅ Output:
3
del: The delete keyword can delete the tuple completely from memory.
💻 Example:
1 2 3 | thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple)
|
✅ Output:
NameError: name 'thistuple' is not defined
.count(): Returns the number of times a specified item occurs in a tuple.
💻 Example:
1 2 | thistuple = ("apple", "banana", "cherry", "banana")
print(thistuple.count('banana'))
|
✅ Output:
2
index(): This method searches specified item & returns the position or index of where it is found. If the item present multiple times in a tuple, the method returns its first occurance index.
💻 Example:
1 2 3 | thistuple = ("apple", "banana", "cherry", "banana")
print(thistuple.index('cherry'))
print(thistuple.index('banana'))
|
✅ Output:
2
1
Here are the quick notes on above topic:
Be prepared with below questions prior to your interview !
Frequently asked Interview Questions
What are sequential data types in python?
What is the difference between python list and tuple?
How do you add elements to a list or tuple?
Can you modify individual elements in a list or tuple?
What is the difference between append() and extend() list method?
How can you check if an element exists in a list or tuple?
Can you remove elements from a list or tuple?
Can we modify a tuple directly?