List and List operations, iteration, traversal in Python

The list is the most useful data collection in python. It acts like an Array and has associated functions to perform multiple operations in the List in Python.

Here we will elaborate the functionality and uses of List.

Let's start with an empty list creation and add String and Dictionary into this:

listitems = []
listitems.append("Lucknow City")
listitems.append({'name':'John'})

Now we have variable listitems that have two different types of values. Let us test size and print these values.

len(listitems)

The output is: 2

len function in python is used to get the size of a List.

Now we will traverse in the list.

for listitem in listitems:
    print(listitem)

Output: 

Lucknow City

{'name': 'John'}

Now you need an index of value then enumerate the list first:

for index,listitem in enumerate(listitems):
    print(index,listitem)

Output: 

0 Lucknow City

1 {'name': 'John'}

Let us merge another list in the listitems.

listitems2 = ["Delhi","Kanpur"]
listitems.extend(listitems2)
print(listitems)

Now listitems will have 4 items.

Output:

['Lucknow City', {'name': 'John'}, 'Delhi', 'Allahabad']

Insert an element to a particular position in the list:

listitems.insert(2,'Kanpur')

It this example value 'Kanpur' is inserted on 2nd position.

Remove an item by name form the List.

listitems.remove('noida')

You can delete items by index also:

del(listitems[2])

You can delete items by index range:

del(listitems[2:4])

Delete all items in the list:

listitems.clear()

Pop item from the list:

listitems.pop()

Pop item from the list with index:

listitems.pop(2)

Sorting in the List:

listitems.sort()

Copy list items into a new variable:

newlist = listitems.copy()

 

 



Keywords: