Lists in Python
Lists in Python
print(n.pop())
print(n)
Output:
Example: pop() method (demo21.py)
n=[1, 2, 3, 4, 5]
print(n.pop(10))
Output:
Difference between remove() and pop()
del V/S remove() the V/Spop()
x[1] = 99
print(x)
print(y)
print(id(x))
print(id(y))
Output:
Cloning in List:
The process of creating duplicate independent objects is called
cloning. We can implement cloning by using the slice operator or
by using the copy() method. These processes create a duplicate
of the existing one at a different memory location. Therefore,
both objects will be independent, and applying any modifications
to one will not impact the other.
Example: Cloning using slicing operator (demo26.py)
x=[10, 20, 30]
y=x[:]
print(x)
print(y)
print(id(x))
print(id(y))
x[1] = 99
print(x)
print(y)
print(id(x))
print(id(y))
Output:
print(id(x))
print(id(y))
Output:
While comparing lists that are loaded with strings the following
things are considered for the comparison.
print(x==y)
print(x==z)
print(x==a)
Output:
True
False
False
MEMBERSHIP OPERATORS IN LIST
We can check if the element is a member of a list or not by using
membership operators. They are:
a. in operator
b. not in operator
If the element is a member of the list, then the in operator
returns True otherwise False. If the element is not in the list,
then not in operator returns True otherwise False.
Example: Membership operators (demo33.py)
x=[10, 20, 30, 40, 50]
print(20 in x) # True
print(20 not in x) # False
print(90 in x) # False
print(90 not in x) # True
Output:
True
False
False
True
for i in x:
y.append(i*2)
print(x)
print(y)
Output:
[1, 2, 3, 4]
[2, 4, 6, 8]
The above code can be written in a single line using list
comprehensions.
Example: List Comprehensions (demo36.py)
x = [1, 2, 3, 4]
y = [ i*2 for i in x]
print(y)
Output:
[2, 4, 6, 8]
l2=[]
for i in l1:
if (i%2 == 0):
l2.append(i*2)
print(l2)
[4, 16, 100]
List Comprehension
numbers = [1, 2, 3, 4, 5]
# create a new list using list comprehension
square_numbers = [num * num for num in numbers]
print(square_numbers)
# Output: [1, 4, 9, 16, 25]
print(l2)
Output
['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
Here, if an item in the numbers list is divisible by 2, it
appends Even to the list even_odd_list. Else, it appends Odd.