DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


What is a Python List?

  • 14 minutes read
  • 24 Views
What is a Python List?

    Table of Contents

What is a Python List?

A Python List is the most common and versatile data structure in Python. It is one of the six built-in types of sequences in Python language. Each item in a Python list is separated by comma (,) and are enclosed in square brackets ([]). It can have any number of items and they may be of different types (integer, float, string etc.). A list can even hold other data structures like Dictionaries or objects like functions, etc.

Are Python lists ordered?

Yes, Python lists are ordered data structures. It means that a Python list keeps the order of the element in which it is added to the list.

Are Python lists mutable?

Yes, lists in Python are mutable and you can add, delete and update an item of a Python List.

Are Python lists hashable?

No, a Python list are not hashable.

Can a Python list hold duplicate items?

Yes, a list in Python can hold multiple number of duplicate items in it.

How to create a Python List?

You can easily create a Python List by enclosing comma-separated elements in square brackets ([])

my_list = [1, 'saral', True, [22, 'gyaan']]

print(my_list)

# Output

[1, 'saral', True, [22, 'gyaan']]

Here you can see that a Python list can hold any kind of element be it integer, string, boolean, another list, etc.

How to create an empty Python List?

If you want to create an empty Python List, you can use the following code:-

a_list = []
b_list = list()

print(a_list, type(a_list))
print(b_list, type(b_list))

# Output

[] <class 'list'>
[] <class 'list'>

How to create a Python List using comprehension

List comprehensions is one of the most elegant and pythonistic way to create a list.

all_squares= [i**2 for i in range(1,11)]
print(all_squares)

# Output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

How to create a Python List using the inbuilt list() method

You can also use the list() method to create a list

a_list = list('saralgyaan')
b_list = list(range(10))
c_list = list((1,2,3))

print(a_list)
print(b_list)
print(c_list)

# Output

['s', 'a', 'r', 'a', 'l', 'g', 'y', 'a', 'a', 'n']
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3]

How to access an element from a Python List?

An element from Python List can be accessed using Index either positive or negative.

Access an element from a Python List using positive index

All the Python Lists are indexed starting from 0 (Zero) to n-1 (where n is the number of elements in the list). So, we can use an Index operator ([]) to access the element. We will get an IndexError if the list does not have the Index mentioned.

my_list = [1, 'saral', True, [22, 'gyaan']]

print(my_list[0])
print(my_list[3])
print(my_list[4])

# Output

1
[22, 'gyaan']
Traceback (most recent call last):
  File "D:\Udit Vashisht\check.py", line 5, in <module>
    print(my_list[4])
IndexError: list index out of range

In order to access the element of the nested list, we will have to use the nested indices.

my_list = [1, 'saral', True, [22, 'gyaan']]

print(my_list[3][1])

# Output

gyaan

Access an element from a Python List using negative index

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

my_list = [1, 'saral', True, [22, 'gyaan']]

print(my_list[-2])
print(my_list[-4])

# Output

True
1

How to do slicing in Python Lists?

We can use the slicing operator - : (colon) to access a range of items in a list. The last index is not included i.e. [1:4] will slice from index 1 to 3.

a_list = list(range(10))

# Slicing all the elements of the list

print(a_list[:])

# Slicing from Index 1 to 4
print(a_list[1:5])

# Slicing upto Index 3

print(a_list[:4])

# Slicing from Index 4 till end

print(a_list[4:])

# Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4]
[0, 1, 2, 3]
[4, 5, 6, 7, 8, 9]

Slicing with steps

Slicing in general take three parameters a_list[start:stop:step]. So, if you want to get alternate elements from the list you can use step. Slicing with steps can also be used to reverse the list by using a negative step (-1)

a_list = list(range(10))

# Slicing out alternate element of the list

print(a_list[::2])

# Using slicing to reverse the list

print(a_list[-1:0:-1])

# Output

[0, 2, 4, 6, 8]
[9, 8, 7, 6, 5, 4, 3, 2, 1]

How to iterate through a Python List?

You can iterate through each element of the Python list using a for loop:-

a_list = list(range(10))

for item in a_list:
    print(item)

# Output

0
1
2
3
4
5
6
7
8
9

In certain use cases, if you need to get the index of the item too, you can use the enumerate function:-

a_list = list(range(1,11))

for index, item in enumerate(a_list):
    print(item, index)

# Output

1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
10 9

How to change an element in Python List?

Since Python Lists are mutable and there elements can be changed using the index of the element to be changed and assignment operator (=).

a_list = list(range(10))

print(a_list)


# Changing a particular element

a_list[3] = 28

print (a_list)

# Changing a range of elements

a_list[1:4] = [7, 7, 7]

print(a_list)

# Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 28, 4, 5, 6, 7, 8, 9]
[0, 7, 7, 7, 4, 5, 6, 7, 8, 9]

How to add a new element to a Python Dictionary

There are mutliple ways to add new element(s) to python dictionary

  • Using append() method
  • Using extend() method
  • Using insert() method
  • Conacetanation (+)
  • Repetition (*)

Adding a single element to Python List using append() method

append() method will add a single element at the end of the python list. It changes the list inplace and doesn’t return anything.

a_list = list(range(10))
a_list.append(8)

print(a_list)

a_list.append([1,3])

print(a_list)

print(a_list.append(9))

print(a_list)

# Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, [1, 3]]
None
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, [1, 3], 9]

Adding multiple elements to a Python List using extend() method

You can add more than one item to a Python list using an extend() method. It takes a list as an input and like append, changes the list inplace.

a_list = list(range(10))

a_list.extend([8,8,8])
print(a_list)

print(a_list.extend([9,9]))

print(a_list)

# Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 8, 8]
None
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 8, 8, 9, 9]

Adding an element at particular index using insert() method

You can add the element at a particular index of a Python list using the insert() method, it takes two variable, the index and the element to be added

a_list = list(range(10))


a_list.insert(5, 88)

print(a_list)

# Output

[0, 1, 2, 3, 4, 88, 5, 6, 7, 8, 9]

Combining two or more lists using concatenation (+)

You can also combine two more lists using the addition operator (+) and the process is called concatenation.

a_list = list(range(10))

b_list = list(range(10,20))

new_list = a_list + b_list

print(new_list)

# Output

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Repeting the elements of the Python List using (*)

You can also repeat the elements of a list using multiplication operator (*)

a_list = ['saral']

new_list = a_list * 5

print(new_list)

# Output

['saral', 'saral', 'saral', 'saral', 'saral']

How to remove/delete an element from a Python List?

There are various methods to delete or remove an element from a Python List like del keyword, pop(), remove(), or clear() method.

Deleting/Removing a Python List element using del keyword

You can remove/delete an element by Index from a Python List using the del keyword. If you would not provide the index, it will delete the whole list.

a_list = list(range(10))

# Deleting single element

del a_list[2]

print(a_list)

# Deleting multiple elements

del a_list[3:6]

print(a_list)

# Deleing the whole list

del a_list

print(a_list)

# Output

[0, 1, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 3, 7, 8, 9]
Traceback (most recent call last):
  File "D:\Udit Vashisht\check.py", line 38, in <module>
    print(a_list)
NameError: name 'a_list' is not defined

Deleting a Python List’s element by Index using pop() method

You can use pop() method to delete the element using the index number. If you won’t use any index, it will remove the last element by default. pop() method also returns the element removed from the list. It is useful when you have to take out an element from the list and use it is some other operation.

a_list = list(range(10))

print(a_list.pop())

print(a_list)

print(a_list.pop(2))

print(a_list)

# Output

9
[0, 1, 2, 3, 4, 5, 6, 7, 8]
2
[0, 1, 3, 4, 5, 6, 7, 8]

Here you can see that the pop() method returned the remove item/element.

Deleting a Python List’s element by value using delete() method

You can also use the delete() method to remove the element by its value. Unlike pop() method, it won’t return the removed element (value). If there are multiple elements with the same value, it will remove the first occurence of the element.

a_list = list('saralgyaan')

print(a_list.remove('n'))

print(a_list)

a_list.remove('a')

print(a_list)

# Output

None                 # It shows that remove() didn't return the removed element
['s', 'a', 'r', 'a', 'l', 'g', 'y', 'a', 'a']
['s', 'r', 'a', 'l', 'g', 'y', 'a', 'a']

Remove/delete all element using clear() method

You can also clear all the contents of a Python List using clear() method. Unlike del, it only deletes the elements and not the list itself and you would be left with an empty list

a_list = list('saralgyaan')

print(a_list)

a_list.clear()

print(a_list)

# Output

['s', 'a', 'r', 'a', 'l', 'g', 'y', 'a', 'a', 'n']
[]

Python List methods

There are various Python List methods as tabulated below:-

append() Add an element to the end of the list
extend() Add all elements of a list to the another list
insert() Insert an item at the defined index
remove() Removes an item from the list
pop() Removes and returns an element at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the number of items passed as an argument
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
copy() Returns a shallow copy of the list

Python Lists built-in functions

Following are the buil-in functions of Python Lists:-

Function Description
reduce() Apply a particular function passed in its argument to all of the list elements stores the intermediate result and only returns the final summation value
sum() Sums up the numbers in the list
ord() Returns an integer representing the Unicode code point of the given Unicode character
cmp() This function returns 1, if first list is “greater” than second list
max() Returns the element with maximum value
min() Returns the element with minimum value
all() Returns True if all element are True or if list is empty
any() Returns True if any element of the list is True. Returns False if list is empty
len() Returns the size or length of the list
enumerate() Returns enumerate object of the list
accumulate() Apply a particular function passed in its argument to all of the list elements returns a list containing the intermediate results
filter() Tests if each element of a list true or not
map() Returns a list of the results after applying the given function to each item of a given iterable
lambda() This function can have any number of arguments but only one expression, which is evaluated and returned.

Basic Python Lists operations

Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration

Related Posts

Matplotlib Subplot in Python | Matplotlib Tutorial | Chapter 10
By Udit Vashisht

Matplotlib Subplot in Python | Chapter 10

In this Matplotlib Subplot tutorial, we will be learning to create Matplotlib Subplots. Till now, we have been using matplotlib.pyplot() to create the plots. But now, we will be using matplotlib.pyplot.subplots() (ptl.subplots()) to create Matplotlib Subplots.

Matplotlib.pyplot() or plt was automatically ...

Read More
How to host and schedule your python script on PythonAnywhere?
By Udit Vashisht

In our last post here, we learned how to create a python script which will automatically delete your messages from gmail account based on a query.

The complete ready-to-use code can be found here.

Follow the steps in the above tutorial to download the ‘credentials.json’ file and ...

Read More
What is a Python Dictionary?
By Udit Vashisht

What is a Python Dictionary?

Python Dictionary is a data-structure in Python that is also known as associative array. A python dictionary is used to store data values in key:value pair. Each item has a key and a corresponding value that is expressed as a pair (key: value). They are ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list