(1) Check If A List Contains An Element.
- The
in
operator will return True if a specific element is in a list.
lst = ['Subrat','Arpita','Abhispa','Subhada']
'Subhada' in lst
True
(2) How To Iterate Over 2+ Lists At The Same Time.
- You can
zip()
lists and then iterate over thezip
object. - A
zip
object is an iterator of tuples. - Below we iterate over 3 lists simultaneously and interpolate the values into a string.
name = ['Snowball', 'Chewy', 'Bubbles', 'Gruff']
animal = ['Cat', 'Dog', 'Fish', 'Goat']
age = [1, 2, 2, 6]
z = zip(name, animal, age)
for i, j, k in z:
print(f"Name: {i} Animal: {j} Age: {k}")
(3) Is A List Mutable?
- Yes.
- Notice in the code below how the value associated with the same identifier in memory has not changed.
x = [1,2]
print(f"List: {x} Address: {id(x)}")
x.append(3)
print(f"List: {x} Address: {id(x)}")
List: [1, 2] Address: 1837796991424
List: [1, 2, 3] Address: 1837796991424
(4) Does A List Need To Be Homogeneous?
- No.
- Different types of object can be mixed together in a list.
a = [1,'a',1.0,[]]
print(a)
a = [1,'a',1.0,[]]
print(a)
(5) What Is The Difference Between Append And Extend?
.append()
adds an object to the end of a list..extend()
adds each value from a 2nd list as its own element. So extending a list with another list combines their values.
Append Method
a = [1,2,3]
print(a)
a.append([4])
print(a)
a = [1,2,3]
print(a)
a.append([4])
print(a)
Extend Method
a = [1,2,3]
print(a)
a.extend([4])
print(a)
[1, 2, 3]
[1, 2, 3, 4]
(5) What Does “del” Do?
- ‘del’ keyword can delete the entire list.
- Or it can be used to delete an element from the list.
Example-1: Deleting An Element
a = [1,2,3]
print(a)
del a[0]
print(a)
[1, 2, 3]
[2, 3]
Example-2: Deleting Entire List
a = [1,2,3]
print(a)
del a
print(a)
[1, 2, 3]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [20], in <cell line: 4>()
2 print(a)
3 del a
----> 4 print(a)
NameError: name 'a' is not defined
(6) What Is The Difference Between “remove” and “pop”?
- .remove() removes the first instance of a matching object.
.pop()
removes an object by its index.
Example-1: remove() Method
a = ['a', 'a', 'b', 'b', 'c', 'c']
print(a)
a.remove('b')
print(a)
['a', 'a', 'b', 'b', 'c', 'c']
['a', 'a', 'b', 'c', 'c']
Example-2: pop() Method
a = ['a', 'a', 'b', 'b', 'c', 'c']
print(a)
a.pop(4)
print(a)
['a', 'a', 'b', 'b', 'c', 'c']
['a', 'a', 'b', 'b', 'c']
Note:
- The difference between
pop
anddel
is thatpop
returns the popped element.
(7) Remove Duplicates From A List
- If you’re not concerned about maintaining the order of a list, then converting to a set and back to a list will achieve this.
Example-1: Using Set
li = [3, 2, 2, 1, 1, 1]
list(set(li))
[1, 2, 3]
Example-1: Using List Comprehinsion
lst = [1,2,1,3,4,7,6,1,3,4,5,5]
print('Original List:', lst)
unique = []
[unique.append(i) for i in lst if i not in unique]
print("Unique List: ",unique)
Original List: [1, 2, 1, 3, 4, 7, 6, 1, 3, 4, 5, 5]
Unique List: [1, 2, 3, 4, 7, 6, 5]
(8) Find The Index Of The 1st Matching Element.
- We can use the index() method to get the index of first matching element.
Example-1:
fruit = ['pear', 'orange', 'apple', 'grapefruit', 'apple', 'pear']
fruit.index('apple')
2
Example-2:
fruit = ['pear', 'orange', 'apple', 'grapefruit', 'apple', 'pear']
fruit.index('kkk')
ValueError Traceback (most recent call last)
Input In [41], in <cell line: 2>()
1 fruit = ['pear', 'orange', 'apple', 'grapefruit', 'apple', 'pear']
----> 2 fruit.index('kkk')
ValueError: 'kkk' is not in list
(9) Remove All Elements From A List.
- .clear() method is used to remove all the element from the list.
Example-1:
fruit = ['pear', 'orange', 'apple']
print(fruit)
fruit.clear()
print(fruit)
['pear', 'orange', 'apple']
[]
(10) Iterate Over Both The Values Indices Of A List.
- enumerate() method is used to get the index and values of the list.
Example-1:
name_list = ['Subrat','Subghada','Arpita']
for idx, val in enumerate(name_list):
print(f'Id: {idx} Value: {val}')
Id: 0 Value: Subrat
Id: 1 Value: Subghada
Id: 2 Value: Arpita
(11) How To Concatenate Two Lists.
- The
+
operator will concatenate 2 lists.
Example-1:
one = ['a', 'b', 'c']
two = [1, 2, 3]
three = one + two
print(three)
['a', 'b', 'c', 1, 2, 3]
(12) Count The Occurrence Of A Specific Object In A List
- The
count()
method returns the number of occurrences of a specific object.
Example-1:
pets = ['dog','cat','fish','fish','cat']
pets.count('fish')
2
(13) How To Shallow Copy A List?
- The
count()
method returns the number of occurrences of a specific object.
Example-1:
names = ['Subrat','Subghada','Arpita','Anuradha']
copy_names = names.copy()
copy_names.remove('Anuradha')
print(f'Names: {names}')
print(f'Copy Names: {copy_names}')
Names: ['Subrat', 'Subghada', 'Arpita', 'Anuradha']
Copy Names: ['Subrat', 'Subghada', 'Arpita']
Note:
- If you change the “copy_name” variable it won’t affect the original variable “names”.
(14) What Is The Difference Between A Deep Copy And A Shallow Copy?
(1) Deep Copy:
- In the case of deep copy, a copy of the object is copied into another object.
- It means that any changes made to a copy of the object do not reflect in the original object.
Syntax Of Deep Copy:
import copy
copy.deepcopy(x)
Examples Of Deep Copy:
import copy
names = ['Subrat','Subghada','Arpita','Anuradha']
copy_names = copy.deepcopy(names)
copy_names.remove('Anuradha')
print(f'Names: {names}')
print(f'Copy Names: {copy_names}')
Names: ['Subrat', 'Subghada', 'Arpita', 'Anuradha']
Copy Names: ['Subrat', 'Subghada', 'Arpita']
(2) Shallow Copy:
- In the case of shallow copy, a reference of an object is copied into another object.
- It means that any changes made to a copy of an object do reflect in the original object.
- In python, this is implemented using the “copy()” function.
Syntax Of Deep Copy:
import copy
copy.copy(x)
Examples Of Deep Copy:
import copy
names = ['Subrat','Subghada','Arpita','Anuradha']
copy_names = names
copy_names.remove('Anuradha')
print(f'Names: {names}')
print(f'Copy Names: {copy_names}')
Names: ['Subrat', 'Subghada', 'Arpita']
Copy Names: ['Subrat', 'Subghada', 'Arpita']
(15) Multiply Every Element In A List By 5 With The Map Function.
- In the case of deep copy, a copy of the object is copied into another object.
- It means that any changes made to a copy of the object do not reflect in the original object.
Example-1:
def multiply_5(val):
return val * 5
a = [10,20,30,40,50]
b = [val for val in map(multiply_5, a)]
print(b)
[50, 100, 150, 200, 250]
(16) Insert A Value At A Specific Index In An Existing List
- The
insert()
method takes an object to insert and the index to insert it at.
Example-1:
li = ['a','b','c','d','e']
li.insert(2, 'HERE')
print(li)
['a', 'b', 'HERE', 'c', 'd', 'e']
(17) Subtract Values In A List From The First Element With The “reduce” Function.
reduce()
needs to be imported fromfunctools
.- Given a function,
reduce
iterates over a sequence and calls the function on every element. - The output from the previous element is passed as an argument when calling the function on the next element.
Example-1:
from functools import reduce
def subtract(a,b):
return a - b
numbers = [100,10,5,1,2,7,5]
reduce(subtract, numbers)
70
Note:
- Above we subtracted 10, 5, 1, 2, 7 and 5 from 100.
Example-1:
from functools import reduce
def subtract(a,b):
return a + b
numbers = [100,10,5,1,2,7,5]
reduce(subtract, numbers)
130
Note:
- Above we add 100, 10, 5, 1, 2, 7 .
(18) Remove Negative Values From A List With The Filter Function
Given a function,
filter()
will remove any elements from a sequence on which the function doesn’t returnTrue
.Below we remove elements less than zero.
Example-1:
def remove_negatives(x):
return True if x >= 0 else False
a = [-10, 27, 100, -1, 0, -30]
b = [x for x in filter(remove_negatives, a)]
print(b)
[27, 100, 0]
(19) Convert A List Into A Dictionary Where List Elements Are Keys.
- For this we can use a dictionary comprehension.
Example-1:
li = ['The', 'quick', 'brown', 'fox', 'was', 'quick']
d = {k:1 for k in li}
print(d)
{'The': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'was': 1}
(20) Modify An Existing List With A Lambda Function.
- Let’s use the map() function to modify the list.
Example-1:
a = [10,20,30,40,50]
b = [x for x in map(lambda x: x*5, a)]
print(b)
[50, 100, 150, 200, 250]
(21) Remove Elements In A List After A Specific Index.
- Using the slice syntax, we can return a new list with only the elements up to a specific index.
Example-1:
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]
li[:10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(22) Remove Elements In A List Before A Specific Index.
- Using the slice syntax, we can return a new list with only the elements up to a specific index.
Example-1:
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]
li[15:]
[16, 17, 18, 19, 10]
(23) Remove Elements In A List Between 2 Indices
- We can mention the start and end index to do this operation.
Example-1:
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,10]
li[12:17]
[13, 14, 15, 16, 17]
(24) Sort A List Of Integers In Ascending Order.
- The
sort()
method mutates a list into ascending order.
Example-1:
li = [10,1,9,2,8,3,7,4,6,5]
li.sort()
li
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(25) Sort A List Of Integers In Descending Order.
- It’s also possible to sort in descending order with
sort()
by adding the argumentreverse=True
.
Example-1:
li = [10,1,9,2,8,3,7,4,6,5]
li.sort(reverse=True)
print(li)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
(26) Filter Even Values Out Of A List With List Comprehension.
You can add conditional logic inside a list comprehension to filter out values following a given pattern.
Here we filter out values divisible by 2.
Example-1:
def even(x):
return True if x % 2 == 0 else False
li = [10,1,9,2,8,3,7,4,6,5]
[x for x in filter(even, li)]
[10, 2, 8, 4, 6]
(27) Count Occurrences Of Each Value In A List.
- We can use dictionary comprehension to do this task
- We can also use the Counter() method to do this operation.
Example-1:
lst = [1, 2, 3, 4, 1, 4, 1]
count = {k:lst.count(lst[v]) for v,k in enumerate(lst) }
print(count)
{1: 3, 2: 1, 3: 1, 4: 2}
Example-2:
from collections import Counter
li = ['blue', 'pink', 'green', 'green', 'yellow', 'pink', 'orange']
Counter(li)
Counter({'blue': 1, 'pink': 2, 'green': 2, 'yellow': 1, 'orange': 1})
(28) Combine Elements In A List Into A Single String.
- This can be done with the
join()
function.
Example-1:
names = ['Subrat','Subghada','Arpita','Anuradha']
joined = "-".join(names)
print(joined)
Subrat-Subghada-Arpita-Anuradha
(29) Use The “any” Function To Return True If Any Value In A List Is Divisible By 2.
- We can combine
any()
with a list comprehension to returnTrue
if any values in the returned list evaluate toTrue
. - Below the 1st list comprehension returns
True
because the list has a2
in it, which is divisible by2
.
Example-1:
li1 = [1,2,3]
truth_table = [i % 2 == 0 for i in li1]
print(truth_table)
any(truth_table)
[False, True, False]
True
Example-2:
li2 = [1,3]
truth_table = [i % 2 == 0 for i in li2]
print(truth_table)
any(truth_table)
[False, False]
False
(30) Use The “all” Function To Return True If All Values In A List Are Negative.
- Similar to the
any()
function,all()
can also be used with a list comprehension to returnTrue
only if all values in the returned list areTrue
.
Example-1:
li1 = [1,2,3]
truth_table = [i > 0 for i in li1]
print(truth_table)
all(truth_table)
[True, True, True]
True
Example-2:
li2 = [1,-2,3]
truth_table = [i > 0 for i in li2]
print(truth_table)
all(truth_table)
[True, False, True]
False
(31) Reverse The Order Of A List.
- A list can be mutated into reverse order with the
reverse()
method.
Example-1:
li = [1,2,3,4,5,6,7,8,9,10]
li.reverse()
print(li)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
(32) What Is The Difference Between Reverse And Reversed?
reverse()
reverses the list in place.-
reversed()
returns an iterable of the list in reverse order.
Example-1:
li = [1,2,3,4,5,6,7,8,9,10]
li.reverse()
print(li)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Example-2:
li = [1,2,3,4,5,6,7,8,9,10]
rev = reversed(li)
print(rev)
list(rev)
<list_reverseiterator object at 0x000001ABE49721F0>
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
(33) What Is The Difference Between sort and sorted?
sort()
modifies the list in place.sorted()
returns a new list in reverse order.
Example-1:
li = [10,1,9,2,8,3,7,4,6,5]
li.sort()
print(li)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example-2:
li = [10,1,9,2,8,3,7,4,6,5]
new_lst = sorted(li)
print(new_lst)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
(34) Return The Minimum Value In A List.
- The
min()
function returns the minimum value in a list.
Example-1:
li = [10,1,9,2,8,3,-7,4,6,5]
min(li)
-7
(35) Return The Maximum Value In A List.
- The
max()
function returns the maximum value in a list.
Example-1:
li = [10,1,9,2,8,3,7,4,6,5]
max(li)
10
(36) Return The Sum Of Value In A List.
- The
sum()
function returns the sum of all values in a list.
Example-1:
li = [10,1,9,2,8,3,7,4,6,5]
sum(li)
55
(37) Find The Intersection Of 2 Lists
- The
sum()
function returns the sum of all values in a list.
Example-1:
li1 = [1,2,3]
li2 = [2,3,4]
set(li1) & set(li2)
{2, 3}
(38) Find The Difference Between A Set And Another Set.
- We can’t subtract lists, but we can subtract sets.
Example-1:
li1 = [1,2,3]
li2 = [2,3,4]
set(li1) - set(li2)
{1}
Example-1:
li1 = [1,2,3]
li2 = [2,3,4]
set(li1) - set(li2)
{1}
(39) Flatten A List Of Lists With A List Comprehensions.
- Unlike Ruby, Python3 doesn’t have an explicit flatten function. But we can use list comprehension to flatten a list of lists.
Example-1:
li = [[1,2,3],[4,5,6]]
[i for x in li for i in x]
[1, 2, 3, 4, 5, 6]
(40) Generate A List Of Every Integer Between 2 Values
- We can create a range between 2 values and then convert that to a list.
Example-1:
list(range(1,10))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
(41) Combine 2 Lists Into A Dictionary
- Using
zip()
and thelist()
constructor we can combine 2 lists into a dictionary where one list becomes the keys and the other list becomes the values.
Example-1:
name = ['Snowball', 'Chewy', 'Bubbles', 'Gruff']
animal = ['Cat', 'Dog', 'Fish', 'Goat']
dict(zip(name, animal))
{'Snowball': 'Cat', 'Chewy': 'Dog', 'Bubbles': 'Fish', 'Gruff': 'Goat'}
(42) Reverse The Order Of A List Using The Slice Syntax
While we can reverse a list with
reverse()
andreversed()
, it can also be done with the slice syntax.This returns a new list by iterating back over the list from end to beginning.
Example-1:
li = [1,2,3,4,5,6,7,8]
li[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]
(43) Find The Smallest Number In A List Using For Loop
- We can use the for loop to iterate over the list and find the smallest number.
Example-1:
lst = [24, 10, 5, 20, 15]
current_min = lst[0]
for num in lst:
if num < current_min:
current_min = num
print(current_min)
5
(44) Sort A List Using For Loop
- We can use the for loop to iterate over the list and find the Sort The Elements.
Example-1:
lst = [24, 10, 5, 20, 15]
temp = 0
for i in range(0, len(lst)):
for j in range (i+1, len(lst)):
if(lst[i] > lst[j]):
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
print(lst)
[5, 10, 15, 20, 24]
Example-2:
lst = [24, 10, 5, 20, 15]
temp = 0
for i in range(0, len(lst)):
for j in range (i+1, len(lst)):
if(lst[i] < lst[j]):
temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
print(lst)
[24, 20, 15, 10, 5]