Python core basics Flashcards
How to check if element exists in list or not?
print(1 in L)
Adding new list to an existing list without creating a new temporary list
l.extend([1,2])
What is the difference between append and extend
In case of append : We will be adding that component as recieved in the input parameters
Whereas in case of extend , it will take the individual components from that list and then add it to the list
Example:
l.append([2,5])
This adds [2,5 ] aka [1,[2,5]]
l.extend([2,5])
The adds 2 and 5 to the list [1,2,5]
How do we delete a certain component in list
del L[0]
How to remove element by passing object itself instead of index of that object in the list
L.remove(“Physics”)
Syntax for removing the last element from a list
L.pop()
What happens if you do B= A.sort() where A and B are lists
A returns the new sorted list
A=[3,4,2] -> A=[2,3,4]
while B returns nothing .
Because its a worthless piece of shit. JK A.sort() is a void function and only changes A, it doesent return an object in return. Only changes the list which is calling the function .
Syntax to sort a list in descending order
L.sort(reverse=True)
What happens if you sort out list which contains words instead of numbers
It arranges the words inside the list in lexographic fashion
Syntax to sort a particular list and store within itself
L.sort()
Syntax to sort a particular list and return list to an object
sorted(L)
What is the difference between lists and tuples?
Lists are immutable , meaning you can access as well as change individual elements
tuples are immutable, meaning while you can access the individual elements , you cant change them.
How do we copy A to B WITHOUT both of them being linked by refence.
or rather
Copying only the elements and maintain them independent of each other… making sure that One is not affected by changing the other
A= [1,2,3]
B= A[:]
B[0]=3
A=[1,2,3] , B=[3,2,3]
If B=[1,2,3]
A = B
B[0] = 3
Then what will be A,B?
A , B will be the same because when we use A=B they are connected by references rather than different objects.
A= [3,2,3]
B= [3,2,3]
What is the syntax if I want to maintain a sorted list as a different object (aka different from the original list object)
C= sorted(A)
A -> Non sorted list Ex : [2,3,1]
C-> Sorted List Ex : [1,2,3]