DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


What is a Python List?

  • 14 minutes read
  • 77 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

How I used Python and Web Scrapping to find cheap diaper deals?
By Udit Vashisht

There were two things which pushed me to write down this code:-
1. Diapers are expensive and saving a dollar or two on it every month is cool.
2. If you are not using python to automate certain stuff, you are not doing it right.

So, here is ...

Read More
Venv Python - A complete tutorial on Virtual Environments in Python
By Udit Vashisht

What is Virtual Environment in Python ?

Virtual Environment is a kind of a container which runs specific version of Python and its modules. And it is used in the cases where you are working on two different project which has different dependencies. Say one of your project uses Django ...

Read More
How to append to a list in Python ? - Python List append() method
By Udit Vashisht

Python List append() method

The Python list append() method adds an item to the end of the list. The length of the list increase by one.

Syntax of append()

The syntax for the same is :-

list_name.append(item) 

Parameters of append()

The method takes only a single argument

...

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 ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python