top of page

Python | Lists

Kritika Rajput

In this post, we will learn about list in python.

  1. Introduction of list

  2. Creating a list

  3. Accessing list elements

  4. Modifying and updating elements of list

Introduction of list:

List is one of the popular data structure in python.

  • It is basically a collection which is ordered and changeable.

  • They are very similar to array but there is major difference, an array can store only one type of elements but list can store different types of elements.

  • They are mutable so we can modifying elements and list are dynamic which means size is not fixed.

  • The elements are separated by commas(,)

  • The list is enclosed in between square brackets[]


Example:-

list_of_python=[2,4,6,8,10]
print(list_of_python)

Output:-

[2,4,6,8,10]
 

Creating a list:-

We can store a different type of elements in a list.

a) List of number:-

list_of_number=[5,10,15,20,25,30]
print (list_of_number)

Output:-

[5,10,15,20,25,30]

b) List of string:-

list_of_string=["java","python","html","c++"]
print (list_of_string)

Output :-

['java', 'python', 'html', 'c++']

c) List of list:-

list_of_list=[[2,"Programmers Door"],[23,4.0]]
print (list_of_list)

Output:-

[[2, 'Programmers Door'], [23, 4.0]]

d) List of mixed elements:-

list_of_mixede_elements=["Programmers Door",5,3.0,"python"]
print (list_of_mixed_elements)

Output:-

['Programmers Door', 5, 3.0, 'python']

e) Empty list:-

Empty_list=[]
print(Empty_list)

Output :-

[]
 

Accessing list element:

To access value in lists,use the square bracket for slicing with the index or indices to obtain value available at that index.


List Index:

We can use the index operator [] to access an item in a list. In python, indices start at 0. So, a list having 5 elements will have an index from o to 4.

a = ["python",22,"machine learning",30]
print (a[3])

Output:

30   

Negative index:

Python allows negative indexing for its sequence. The index of -1 refers to the last item , -2 to the second last item and so on.

For example:-

list_of_item = ["ab","cd","ef","gh","ij"]
print (list_of_item[-3])

Output:

ef
 

Modifying or updating element:

Modifying a list means to change particular entry, add a new entry, or remove an existing entry.

Example :-

a = [10,40,50,80,100]
a[2] = 60
print(a)

Output:

[10, 40, 60, 80, 100]
 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

12 views0 comments

Recent Posts

See All

Comments


bottom of page