Python Lists : Part - 1

What are lists?

In Python, lists are used to store multiple items in a single variable. All values in a list are called elements. Lists are created using square brackets or '[]' For example;

mylist=["apple","mango","litchi"]

In the above list, the elements are, "apple", "mango" and "litchi".

Items in a List

Items in a list are ordered, changeable and allow duplicates. The first item of the list is indexed as 0, not 1, the second as 1 and so on.

What does ordered mean?

In case of lists in Python, ordered means that the items have a definite order and any new elements will be added at the end. For example;

L=[1,2,3,4,5]
L.extend([1,3])
print(L)

Output:

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

What does changeable mean?

Changeable means that a list can be modified and elements can be added to it and deleted from it.

Length of a list

The length of a list can be obtained by using the len() function. For example;

l=[1,2,3,4,5,6]
print(len(l))

Output:

6

Accessing list items

Indexing of list elements

List items are indexed and can be accessed by using their index number. The first element is numbered as 0, the second as 1 and so on. For example;

list=["red","green","blue","yellow"]
print(list[0])

Output:

red

Negative indexing in lists

In Python Lists, negative indexing starts from the last element. The last element of the list is indexed as -1, the second last as -2 and so on. For example;

list=["red","green","blue","yellow"]
print(list[-1])

Output;

yellow

Accessing a range of elements

You can access a range of elements by specifying where to start and where to end. For example;

list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(list[1:5])

Output:

['banana', 'cherry', 'orange', 'kiwi']

In the above code, the elements that are printed will start from index number 1(included) i.e. the second element and end with index number 5(not included).

Checking if an item exists in a list

We can check if an item exists in a list by using the 'in' operator. For example-

list=["red","green","blue","yellow"]
if "green" in list:
  print("Yes, green is there in the list.")
else:
  print("No, green is not there in the list.")


That is all for this post on lists in Python. Hope you find it informative and easy to understand. If you have any reviews/suggestions please consider filling the contact form on the right side of the page or comment below.

Regards,

Aarav Iyer

Aarav Iyer

I am a technology and programming enthusiast, currently a high school student. I love drawing and am quite interested in aeronautics and astrophysics too. My favourite pastimes are reading books, blogging and skywatching with my telescope.

Post a Comment

Next Post Previous Post