In this tutorial we are going to learn : 

  • Adding and Removing Items
  • Finding Item in a List
  • Sorting List
  • Zip Function

 

 

Adding Items to a List

 

  • append() : add an item to the end of the list.
  • insert () : add an item at the specified index.

 

Example :

my_list = [1, 2, 3, 4, 5]

# Adding Item
my_list.append("a")     # Adding item end of the my_list
print(my_list)

my_list.insert(0, "b")  # Adding item specific location
print(my_list) 

 

 

 

Removing Items

 
  • pop () : removes the specified index ( if index is not specified, removes the last item . )
  • remove () : removes the specified items
  • del : keyword removes the specified index ( or range of item )
  • clear () : removes all items from the list.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Removing Items

my_list.pop()       # Removing item at the end of the list
print(my_list)

my_list.pop(0)      # Also removing item at the giving index
print(my_list)

my_list.remove(3)   # Removing item if it is available in list
print(my_list)

del my_list[2:4]    # Removing a range of item
print(my_list)

my_list.clear()     # Removing all the items in the list 
print(my_list)
 

 

 

 

Finding an item in a list

 

If we want to learn the item that we are looking for is in the list, we use the in keyword.

Example :

As you can see the item we are looking for is in index 0 .

my_list = ["James", "John", "Adam"]

if "James" in my_list:
    print(my_list.index("James")) 

 

 

 

Sorting List

 

To organize the list’s items as ascended or descended orders, you can use the sort()
function.

Example :

my_list = [2, 12, 7, 5, 26, 4]

my_list.sort()                      # Ascended order
print("Ascended order :", my_list)

my_list.sort(reverse= True)         # Descended order
print("Descended order :", my_list) 

 

 


Zip Function


You can use the zip() function to combine two lists as a tuple.

Example :

first_list = [1, 2, 3, 4, 5]
second_list = [10, 20, 30, 40, 50]

combine = list(zip(first_list, second_list))
print(combine)


last = list(zip("abcde", first_list, second_list))
print(last) 
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments