Programming, Python, Tutorials

All about List Data type in Python

Lists data type is python is similar to arrays in many other programming languages.

Lists are mutable sequences used to store items of the different or same data types.

Properties of list data type

  • is Ordered
  • Is Mutable
  • Can be Homogenous or heterogenous
  • Can be used as stack
  • Can be used as Queue
  • Can be Nested

How to Create a list in python?

In pyhton lists can be made in 4 different ways.

Python list indexing
  • Using a square bracket : [ ]
  • Separating items with a comma in a square bracket. [ 1, 2, 3, “a”, “b” ]
  • Using list comprehension. [ x for x in iterable ]
  • Using type constructor: list() or list( iterable )

5 ways to create a list.

Accessing items of a list

Each item in a list can be accessed by its index value.

With index values python offers different techniques to manipulate and access the items of list.

Python list slicing
  • Negative Indexing– To access elements from the last of the list.
    • eg.- list_items[-2] will return the 2nd last item of the list.
  • Slicing – To access a limited range of items.
    • list_items[1:10] – list of items from index 2 to index 9
    • list_items[ :5 ] – list of items from index 0 to index 4
    • list_items[-5: ] -list of items from 5th item from last to last item

Changing item value in a list

Since each element of a list can be changed by using the ‘=’ operator.

Eg. list_items[1]=10 will change the value of item at index 1 to ’10’

Add item in a list

To add elements in a python list “append()” or ” extend()” can be used .

  • append(item) will add item/ items at the end of the list.
  • extend(iterable) will append values returned by the iterable.

Delete items of a list

del statement removes a value from the list given the index.

del list_items[index] removes item at specified index .

Get length of the list

len() function returns the number of items in a list

Sort values in a list

sort() method sorts the values in ascending or descending order.

Note.: sort only works when the list is homogeneous.

More useful methods of list

MethodUsage
append(item)add item at the end of the list
extend(iterable)add item from an iterable to end of list
insert(i,x)before index ‘i’ add item ‘x’
remove(x)remove item from list whose value is x
pop()removes last item from the list
clear()remove all items of the list
index(x)returns index at which value is equal to x
count(x)counts number of times x appears in the list
sort()sorts the list
reverse()reverse elements of the list
Methods in Python

Thank you for reading, Happy Learning, drop your suggestion in the comments.

Feel free to follow us on Youtube , Linked In , Instagram

0 0 vote
Article Rating