Python Mutable

  • Python Mutable data types are those whose values can be changed in place.
  1. Lists
  2. Sets
  3. Dictionaries

List

  • A list is a collection that is ordered, changeable, and Allows duplicate members.
  • The lists are written with square brackets [ ].
Example

Create a list

y=[1,2,3,4,5,6,7] #This is a list

print(y)
Output
[1, 2, 3, 4, 5, 6, 7]

How to Access List Items

  • To access list items by using index numbers, inside square brackets.
Example

Create a Tuple

t=["amit", "sumit", "ravi"]
print(t[2])
Output
ravi

To access List of a member by using for loop.

Example

Create a list and access using for loop

t=["amit", "sumit", "ravi"]
for i in t:
 print(i)
Output
amit
sumit
ravi

Check if control statement in List

  • Using in keywords to determine if a specified item is present in a List.
Example

Create a List and use if control statements

t=["amit", "sumit", "ravi"]
if "sumit" in t:
 print("Yes, 'sumit' is found in list")
else:
 print("No, 'sumit' is found in list")
Output
Yes, ‘sumit’ is found in list

How to Change Item Value in List

  • To change list items by using index numbers, inside square brackets.
Example

Change item in List

t=["amit", "sumit", "ravi"]
print(t)
t[1]="ram"
print(t)
Output
[‘amit’, ‘sumit’, ‘ravi’]
[‘amit’, ‘ram’, ‘ravi’]