List is one of the built-in data types in Python. A Python list is a sequence of comma separated items, enclosed in square brackets [ ]. The items in a Python list need not be of the same data type.
Change list items
Contents of list can be modified in place, after the object is stored in the memory. You can assign a new value at a given index position in the list.
list1 = ["a", "b", "c", "d"]
print ("Original list: ", list1)
list2 = ['Z']
list1[1:3] = list2
print ("List after changing with sublist: ", list1)
Result:
Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'Z', 'd']
List class methods:
There are two methods of the list class, append()
and insert()
, that are used to add items to an existing list.
append()
method adds the item at the end of an existing list.insert()
method inserts the item at a specified index in the list.list class methods remove() and pop() both can remove an item from a list.
remove()
removes the object given as argumentpop()
removes an item at the given index.You can also use del mylist[1]
Ex:
mylist = [12, 22.7, "Sunil", "ABC"]
mylist.remove("ABC") -> [12, 22.7, "Sunil"]
mylist.pop(2) -> [12, 22.7]
del mylist[1] -> [12]
sort()
method of list class rearranges the items in ascending or descending order.copy()
method to create a new physical copy of a list object.list = []
mylists = [34,"Sunil",23.2, "Test1", "Test2", "Test3"]
print("My lists 1st - ",mylists[0])
print("My lists 1st - ",mylists[1])
print("My lists 1st - ",mylists[1:])
print("My lists 1st - ",mylists[:1])
new_lists = ["Test2", 32]
print("Concatinated list : ",mylists+new_lists)
mylists[1] = "Test3"
print(mylists)
mylists.append("Test4")
print("My appended lists 1st - ",mylists)
mylists.pop()
print("New lists after pop",mylists)
# you can assign pop value - last value to new variable
pop_list=mylists.pop()
print("Popped value : ",pop_list)
mynumlists = [145,12,42,3,45]
mynumlists.sort()
mynumlist=mynumlists
print(mynumlist)
# Nested list
Nested_list = [['one', 'two', 'three'], [1,1.1,3],[1,2,3]]
print(type(Nested_list))
print("Nested loop [0][1] :",Nested_list[0][1])
print("Nested loop [1][1] :",Nested_list[1][1])
print("Nested loop [2][2] :",Nested_list[2][2])
Result:
My lists 1st - 34
My lists 1st - Sunil
My lists 1st - ['Sunil', 23.2, 'Test1', 'Test2', 'Test3']
My lists 1st - [34]
Concatinated list : [34, 'Sunil', 23.2, 'Test1', 'Test2', 'Test3', 'Test2', 32]
[34, 'Test3', 23.2, 'Test1', 'Test2', 'Test3']
My appended lists 1st - [34, 'Test3', 23.2, 'Test1', 'Test2', 'Test3', 'Test4']
New lists after pop [34, 'Test3', 23.2, 'Test1', 'Test2', 'Test3']
Popped value : Test3
[3, 12, 42, 45, 145]
< class 'list'>
Nested loop [0][1] : two
Nested loop [1][1] : 1.1
Nested loop [2][2] : 3
Main Page | Next Chapter: Python - Dictionaries |