List Operations In Python

List support different operations such as adding, slicing, deleting and popping values in lists.

Adding values in list

Adding operations is used to add value in the list. You can add a single variable and add to list to another list.

Slicing values in list

Slicing operation is used to retrieve values from the list. You can retrieve single and multiple values from the list.

Deleting values in list

Deleting operation is used to delete values in the list. You can delete the value that why the list is changeable collection variable, unlike tuple.

Popping values in list

Popping operation is used to retrieve the value and remove it from list after retrieval. Index of list element can be used to retrieve the specific value of list. Passing index to pop function is optional, by default return and remove last element.


# # Adding
# adding values in list
cities = ["London","Paris"]
cities.append("Islamabad")
print(cities)

# adding multiple values in list
numbers = [11]
print(numbers)
numbers = numbers + [12,13,14,15]
print(numbers)

# adding values in empty list
names = []
names =  names + ["John", "Asad", "David","Winston"]
print(names)

# adding value where you want to add with insert function
names.insert(0,"Raza")
print(names)

# adding value at position 2
names.insert(1,"Awais")
print(names)

# adding value after David
names.insert(5,"Avery")
print(names)

# # Slicing
#  print only two names
print(names[0:2])

# print last name
print(names[-1])

# print first 5 names
print(names[:5])

# print values from 3 to last
print(names[2:])

# # Deleting

# delete Third element 'John' of list
print("List before delete operation")
print(names)
del names[2]
print("List after delete operation")
print(names)

# delete value with remove method
names.remove("Raza")
print(names)


# # Popping

# pop fuction by default give last value of list
last_value = names.pop()
print(last_value)

# pop values from one list to save in other list
students = names.pop(1)
print(students)


Github:
https://github.com/asadraza825/python/blob/master/list_operations.ipynb
Tags: Python, Python Programming,  Python Lists, List operations
Next Post Previous Post
No Comment
Add Comment
comment url