Pyhthon List Tutorial For Beginners

(Lisa Mathew) #1

List is the an important and often used sequence data type( Python lists lets you store data separated by comas in square brackets.

Python List Tutorial

This tutorial will help you understand the basic operations using python lists.

Creating a Python List

You can create a python list using the following syntax.

demo_list = [ ]

You can have any type of data in the list. for example, integers, strings, floating point data etc.

demo_data = [ "scriptcrunch", 4, 7, "3.4", "davis"]

Also you can have nested lists like the following.

demo_list = [ "scriptcrunch", [ 1, 2, 3], [3.2, 4.3, 6.7] ]

Accessing List Elements

All the elements in the list are indexed from 0 to n. the first element has the index 0 and gets incremented based on the list size.

So, basically, if you want to access an element in a list, you can access it with the respective index number.

For example,

print(demo_list[0]) will print the first element of the list.

print(demo_list[5]) will print the 6th element on the list.

You can also use negative indexing, which will start from the end of the list.

For example,

print(demo_list[-1]) would return the last element in the list. -2 would return the second last element and so on.

Till now, we have learned the basics of list data type. Next, we will look into List operations.

You can also access a range of elements using the slicing operator - colon.

For example,

print(demo_list[1:3]) would return elements from 1st to 3rd index.

print(demo_list[:-2]) would return elements till second last index.

pring(demo_list[4:]) would print elements from 4 th index till the end.

List Operations

you cna learn more about list operations from here