List and tuple both are sequence in python. The key difference is lists are mutable type and tuples are immutable type. Tuples do not support assignment like Lists. The literal syntax of list is shown by square brackets ' [ ] ' and tuple is shown by parenthesis ' ( ) '.
List
l1 = [1,2,3,4,5]
l2 = ['s', 2, ['sam', (1,2)]]
Tuple
t1 = (1, 'tiger', 4.0)
t2 = ('a', 'e', 'i', 'o', 'u')
Everything in python is an object. The objects which cannot be changed once created is called immutable type and the objects which can be changed after creation are called mutable type.
Mutable data types- list, dict, set, byte array
Immutable data types- int, float, complex, string, tuple, frozen set , bytes
Append and extend both are the methods of list data type. Append add argument as a single element at the end of a list instance. Extend iterates over its argument and add each element to the end of the list.
Append
List1 = ['fan', 'box']
List1.append('ball')
print(list1)
list2 = [1, 2, 3, 4]
list1.append(list2)
print(list1)
Extend
List1 = ['fan', 'box']
list2 = [1, 2, 3, 4]
list1.extend(list2)
print(list1)
list1.extend('ball')
print(list1)
When argument of a function take the reference of an object is called “call by reference” and changing it inside a function will change the object outside.
def change_list(list1):
list1 += [12]
n = [4, 5, 6]
print(id(n))
change_list(n)
print(n)
print(id(n))
When argument of a function take only the value of an object is called “call by value” and changing it inside a function will not affect the object outside.
def change_number(n):
print(id(n))
n += 10
a = 9
print(id(a))
change_number(a)
print(a)
print(id(a))
Both the methods returns the index number of the substring when it find the first occurrence of the substring. But Find method returns ‘-1’ when it does not find the substring but index method gives a value error in this scenario.
s1 = 'I love swimming'
print(s1.find('n')) # -1
print(s1.index('n')) # ValueError: substring not found
my_list = [1, 2, 3, 4, 5, 6]
my_list.remove(2)
print(my_list) # [1, 3, 4, 5, 6]
my_list.pop(2) # will remove the element with index no ‘2’
print(list) # [1, 3, 5, 6]
del my_list(1) # will delete the element with index no ‘1’
print(list) # [1, 5, 6]
my_list[1:2] = [] # will remove the element with index no ‘1’
print(list) # [1, 6]
my_list = [1, 2, 3, 4, 5, 6]
another_list = [7, 8 , 9]
# include the second list in the first list after the element ‘3’
Method-1
my_list = mylist[0:3] + another_list + mylist[3:]
print(new_list) # [1, 2, 3, 7, 8, 9, 4, 5, 6]
Method-2
my_list = [1, 2, 3, 4, 5, 6]
my_list[3:4]= another_list
print(my_list) # [1, 2, 3, 7, 8, 9, 4, 5, 6]
List comprehension is a concise way of generating a list from an iterator.
Square of numbers
Using for loop
list1 = []
for i in range(1,5):
list1.append(i*i)
print(list1)
Using list comprehension
Print([i*i for i in range(1,5) ])
Find odd numbers
Using for loop
list1 = []
for i in range(1,6):
if i % 2 !=0:
list1.append(i)
print(list1)
Using list comprehension
Print([i for i in range(1,5) if i % 2 !=0 ])
Like list comprehension dictionary can be formed from a iterator in one line.
dict1 = {x: x**2 for x in (2, 4, 6)}
print(dict1) #{2: 4, 4: 16, 6: 36}
A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets.To create an empty set you have to use set(), not {}.
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # {'orange', 'banana', 'pear', 'apple'}
a = set('abracadabra')
print(a) #{'a', 'r', 'b', 'c', 'd'}
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack) # [3, 4, 5, 6, 7]
stack.pop()
print(stack) # [3, 4, 5, 6]
stack.pop() # 6 removed
stack.pop() # 5 removed
print(stack) # [3, 4]
It is possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); However, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends.
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry") # Terry arrives
queue.append("Graham") # Graham arrives
queue.popleft() # The first to arrive now leaves ('Eric')
queue.popleft() # The second to arrive now leaves ('John')
print(queue) # deque(['Michael', 'Terry', 'Graham'])
Iterable is an object, from which we can get an iterator.
List, string, tuple, dictionary, set are iterable data types. Integer is a non iterable data type