Python List with Examples – A Complete Python List Tutorial

Free Python courses with 57 real-time projects - Learn Python

In today’s tutorial, we will learn about Python list. We will discuss how to create, access, slice, and reassign list in Python. Then we will see how to apply functions to them.  Along with this, we will discuss Python List Operations and Concatenation.

So, let’s start the Python List Tutorial.

Python List with Examples - A Complete Python List Tutorial

Python List with Examples – A Complete Python List Tutorial

What is Python List?

Unlike C++ or Java, Python Programming Language doesn’t have arrays. To hold a sequence of values, then, it provides the ‘list’ class. A Python list can be seen as a collection of values.

1. How to Create Python List?

To create python list of items, you need to mention the items, separated by commas, in square brackets. This is the python syntax you need to follow. Then assign it to a variable. Remember once again, you don’t need to declare the data type, because Python is dynamically-typed.

>>> colors=['red','green','blue']

A Python list may hold different types of values.

>>> days=['Monday','Tuesday','Wednesday',4,5,6,7.0]

A list may have python list.

>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
>>> languages

Output

[[‘English’], [‘Gujarati’], [‘Hindi’], ‘Romanian’, ‘Spanish’]
>>> type(languages[0])

Output

<class ‘list’>

A list may also contain tuples or so.

>>> languages=[('English','Albanian'),'Gujarati','Hindi','Romanian','Spanish']
>>> languages[0]

Output

(‘English’, ‘Romanian’)
>>> type(languages[0])

Output

<class ‘tuple’>
>>> languages[0][0]='Albanian'

Output

Traceback (most recent call last):File “<pyshell#24>”, line 1, in <module>

languages[0][0]=’Albanian’

TypeError: ‘tuple’ object does not support item assignment

2. How to Access Python List?

To access a Python list as a whole, all you need is its name.

>>> days

Output

[‘Monday’, ‘Tuesday’, ‘Wednesday’, 4, 5, 6, 7.0]

Or, you can put it in a print statement.

>>> languages=[['English'],['Gujarati'],['Hindi'],'Romanian','Spanish']
>>> print(languages)

Output

[[‘English’], [‘Gujarati’], [‘Hindi’], ‘Romanian’, ‘Spanish’]

To access a single element, use its index in square brackets after the list’s name. Indexing begins at 0.

>>> languages[0]

Output

[‘English’]

An index cannot be a float value.

>>> languages[1.0]

Output

Traceback (most recent call last):File “<pyshell#70>”, line 1, in <module>

languages[1.0]

TypeError: list indices must be integers or slices, not float

3. Slicing a Python List

When you want only a part of a Python list, you can use the slicing operator [].

>>> indices=['zero','one','two','three','four','five']
>>> indices[2:4]

Output

[‘two’, ‘three’]

This returns items from index 2 to index 4-1 (i.e., 3)

>>> indices[:4]

Output

[‘zero’, ‘one’, ‘two’, ‘three’]

This returns items from the beginning of the list to index 3.

>>> indices[4:]

Output

[‘four’, ‘five’]

It returns items from index 4 to the end of the list in Python.

>>> indices[:]

Output

[‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’]

This returns the whole list.

  • Negative indices- The indices we mention can be negative as well. A negative index means traversal from the end of the list.
>>> indices[:-2]

Output

[‘zero’, ‘one’, ‘two’, ‘three’]

This returns item from the list’s beginning to two items from the end.

>>> indices[1:-2]

Output

[‘one’, ‘two’, ‘three’]

It returns items from the item at index 1 to two items from the end.

>>> indices[-2:-1]

Output

[‘four’]

This returns items from two from the end to one from the end.

>>> indices[-1:-2]

Output

[]

This returns an empty Python list, because the start is ahead of the stop for the traversal.

4. Reassigning a Python List (Mutable)

Python Lists are mutable. This means that you can reassign its items, or you can reassign it as a whole. Let’s take a new list.

>>> colors=['red','green','blue']

a. Reassigning the whole Python list

You can reassign a Python list by assigning it like a new list.

>>> colors=['caramel','gold','silver','occur']
>>> colors

Output

[‘caramel’, ‘gold’, ‘silver’, ‘occur’]

b. Reassigning a few elements

You can also reassign a slice of a list in Python.

>>> colors[2:]=['bronze','silver']
>>> colors

Output

[‘caramel’, ‘gold’, ‘bronze’, ‘silver’]

If we had instead put two values to a single one in the left, see what would’ve happened.

>>> colors=['caramel','gold','silver','occur']
>>> colors[2:3]=['bronze','silver']
>>> colors

Output

[‘caramel’, ‘gold’, ‘bronze’, ‘silver’, ‘occur’]

colors[2:3] reassigns the element at index 2, which is the third element.

2:2 works too.

>>> colors[2:2]=['occur']
>>> colors

Output

[‘caramel’, ‘gold’, ‘occur’, ‘bronze’, ‘silver’]

c. Reassigning a single element

You can reassign individual elements too.

>>> colors=['caramel','gold','silver','occur']
>>> colors[3]='bronze'
>>> colors

Output

[‘caramel’, ‘gold’, ‘silver’, ‘bronze’]

Now if you want to add another item ‘holographic’ to the list, we cannot do it the conventional way.

>>> colors[4]='holographic'

Output

Traceback (most recent call last):File “<pyshell#2>”, line 1, in <module>

colors[4]=’holographic’

IndexError: list assignment index out of range

So, you need to reassign the whole list for the same.

>>> colors=['caramel','gold','silver','bronze','holographic']
>>> colors

Output

[‘caramel’, ‘gold’, ‘silver’, ‘bronze’, ‘holographic’]

3. How can we Delete a Python List?

You can delete a Python list, some of its elements, or a single element.

a. Deleting the entire Python list

Use the del keyword for the same.

>>> del colors
>>> colors

Output

Traceback (most recent call last):File “<pyshell#51>”, line 1, in <module>

colors

NameError: name ‘colors’ is not defined

b. Deleting a few elements

Use the slicing operator in python to delete a slice.

>>> colors=['caramel','gold','silver','bronze','holographic']
>>> del colors[2:4]
>>> colors

Output

[‘caramel’, ‘gold’, ‘holographic’]
>>> colors[2]

Output

‘holographic’

Now, ‘holographic’ is at position 2.

c. Deleting a single element

To delete a single element from a Python list, use its index.

>>> del colors[0]
>>> colors

Output

[‘gold’, ‘holographic’]

Multidimensional Lists in Python

You can also put a list in a list. Let’s look at a multidimensional list.

>>> grocery_list=[['caramel','P&B','Jelly'],['onions','potatoes'],['flour','oil']]
>>> grocery_list

Output

[[‘caramel’, ‘P&B’, ‘Jelly’], [‘onions’, ‘potatoes’], [‘flour’, ‘oil’]]

This is a grocery Python list with lists in it, where the lists are according to a category.

Or, you can choose to go deeper.

>>> a=[[[1,2],[3,4],5],[6,7]]
>>> a

Output

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

To access the element 4 here, we type the following code into the shell.

>>> a[0][1][1]

Output

4

Concatenation of Python List

The concatenation operator works for lists as well. It lets us join two lists, with their orders preserved.

>>> a,b=[3,1,2],[5,4,6]
>>> a+b

Output

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

Python List Operations

a. Multiplication

This is an arithmetic operation. Multiplying a Python list by an integer makes copies of its items that a number of times while preserving the order.

>>> a*=3
>>> a

Output

[3, 1, 2, 3, 1, 2, 3, 1, 2]

However, you can’t multiply it by a float.

>>> a*3.0

Output

Traceback (most recent call last):File “<pyshell#89>”, line 1, in <module>

a*3.0

TypeError: can’t multiply sequence by non-int of type ‘float’

b. Membership

You can apply the ‘in’ and ‘not in’ operators on a Python list.

>>> 1 in a

Output

True
>>> 2 not in a

Output

False

Iterating on a list

Python list can be traversed with a for loop in python.

>>> for i in [1,2,3]:
         if i%2==0:
                print(f"{i} is composite\n")

Output

2 is composite

Python List Comprehension

You can create a new list just like you would do in mathematics. To do so, type an expression followed by a for statement, all inside square brackets. You may assign it to a variable. Let’s make a list for all even numbers from 1 to 20.

>>> even=[2*i for i in range(1,11)]
>>> even

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Optionally, you can add an if-statement to filter out items. If we want to change this list to hold only those items from 1 to 20 that are even and are divisible by 3, we write the following code.

>>> even=[2*i for i in range(1,11) if i%3==0]
>>> even

Output

[6, 12, 18]

Built-in List Functions

There are some built-in functions in Python that you can use on python lists.

Python List Tutorial - Built-in List Functions

Python List Tutorial – Built-in List Functions

a. len()

It calculates the length of the list.

>>> len(even)

Output

3

b. max()

It returns the item from the list with the highest value.

>>> max(even)

Output

18

If all the items in your list are strings, it will compare.

>>> max(['1','2','3'])

Output

‘3’

But it fails when some are numeric, and some are strings in python.

>>> max([2,'1','2'])

Output

Traceback (most recent call last):File “<pyshell#116>”, line 1, in <module>

max([2,’1′,’2′])

TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

c. min()

It returns the item from the Python list with the lowest value.

>>> min(even)

Output

6

d. sum()

It returns the sum of all the elements in the list.

>>> sum(even)

Output

36

However, for this, the Python list must hold all numeric values.

>>> a=['1','2','3']
>>> sum(a)

Output

Traceback (most recent call last):File “<pyshell#112>”, line 1, in <module>

sum(a)

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

It works on floats.

>>> sum([1.1,2.2,3.3])

Output

6.6

e. sorted()

It returns a sorted version of the list, but does not change the original one.

>>> a=[3,1,2]
>>> sorted(a)

Output

[1, 2, 3]
>>> a

Output

[3, 1, 2]

If the Python list members are strings, it sorts them according to their ASCII values.

>>> sorted(['hello','hell','Hello'])

Output

[‘Hello’, ‘hell’, ‘hello’]

Here, since H has an ASCII value of 72, it appears first.

f. list()

It converts a different data type into a list.

>>> list("abc")

Output

[‘a’, ‘b’, ‘c’]

It can’t convert a single int into a list, though, it only converts iterables.

>>> list(2)

Output

Traceback (most recent call last):File “<pyshell#122>”, line 1, in <module>

list(2)

TypeError: ‘int’ object is not iterable

g. any()

It returns True if even one item in the Python list has a True value.

>>> any(['','','1'])

Output

True

It returns False for an empty iterable.

>>> any([])

Output

False

h. all()

It returns True if all items in the list have a True value.

>>> all(['','','1'])

Output

False

It returns True for an empty iterable.

>>> all([])

Output

True

Built-in Methods

While a function is what you can apply on a construct and get a result, a method is what you can do to it and change it. To call a method on a construct, you use the dot-operator(.). Python supports some built-in methods to alter a Python list.

Python List - Built-in Methods

Python List – Built-in Methods

a. append()

It adds an item to the end of the list.

>>> a

Output

[2, 1, 3]
>>> a.append(4)
>>> a

Output

[2, 1, 3, 4]

b. insert()

It inserts an item at a specified position.

>>> a.insert(3,5)
>>> a

Output

[2, 1, 3, 5, 4]

This inserted the element 5 at index 3.

c. remove()

It removes the first instance of an item from the Python list.

>>> a=[2,1,3,5,2,4]
>>> a.remove(2)
>>> a

Output

[1, 3, 5, 2, 4]

Notice how there were two 2s, but it removed only the first one.

d. pop()

It removes the element at the specified index, and prints it to the screen.

>>> a.pop(3)

Output

2
>>> a

Output

[1, 3, 5, 4]

e. clear()

It empties the Python list.

>>> a.clear()
>>> a

Output

[]

It now has a False value.

>>> bool(a)

Output

False

f. index()

It returns the first matching index of the item specified.

>>> a=[1,3,5,3,4]
>>> a.index(3)

Output

1

g. count()

It returns the count of the item specified.

>>> a.count(3)

Output

2

h. sort()

It sorts the list in an ascending order.

>>> a.sort()
>>> a

Output

[1, 3, 3, 4, 5]

i. reverse()

It reverses the order of elements in the Python lists.

>>> a.reverse()
>>> a

Output

[5, 4, 3, 3, 1]

This was all about the Python lists

Python Interview Questions on Lists

  1. What are lists in Python? Explain with example.
  2. How to get the elements of a list in Python?
  3. How to make a list in a list Python?
  4. What are lists used for in Python?
  5. What are lists called in Python?

Conclusion

Woah, that was a lot, wasn’t it? Let’s make a quick revision so you don’t forget it.

In this lesson on Python Lists, we first looked at how to declare and access a list. That included slicing lists in python. Then we looked at how to delete and reassign elements or an entire list.

Next, we learned about multidimensional lists and comprehension. We saw how to iterate on python lists, concatenate them, and also the operations that you can perform on them.

Lastly, we looked at some built-in functions and methods that you can call on lists. Hope you enjoyed, see you again.

Furthermore, if you have any query, feel free to ask in the comment section

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

20 Responses

  1. sriyam says:

    Hi All,
    I was asked the below questions in an interview which i could not answer. Can you please provide the answers to me for this.
    1)There is a string such My Name Is Sriyam”. How would i write a program such that it would print the first character of each word in the string. such as M,N,I,S
    2) How can you copy an image from one folder to another in python.

    • Sumit Khajanchi says:

      >>> a = “My Name Is Sumit”
      #We can divide this strings into 4 pieces using split, and then print first character of each.
      >>> for i in a.split(” “):
      print(i[0])
      M
      N
      I
      S

    • Data Flair says:

      Hello, Sriyam
      We Glad you asked your query to us.
      You can use the following piece of code for your first question:
      >>> s=’My Name Is Sriyam’
      >>> for i in s.split(‘ ‘):
      print(i[0])
      As for your second query, you can use shutil. Suppose we have two folders ‘a’ and ‘b’. To move an image ‘df.png’ from ‘a’ to ‘b’, you can:
      >>> shutil.copy(‘a\\df.png’,’b’)
      Now, you can answer every question tossed at you in an interview for Python. We have launched a new series of commonly asked Python Interview Questions and Answers. The series is full of tricky questions so you can prepare yourself for upcoming Python Interviews.

  2. ABDULLAH says:

    It is very useful for me and it’s also be in easy language

    • Data Flair says:

      We are Happy to hear that you like our article on “Python Lists”. We Hope the Slicing List and built-in Functions & Methods help you.
      Each Appreciation Contributes to Our Motivation.

  3. Sibin Paul says:

    Clarification needed for the below topic
    C. Reassigning a single element :
    The list mentioned in the example is colors. But you are attempted to add a new element into the list color.
    color[4]=’holographic’
    If we add a new element to the list colors, it will show the following error.
    IndexError: list assignment index out of range

    • DataFlair Team says:

      Thanks for pointing out and helping us for the correction. It was our typo and we made necessary changes.
      Keep visiting Dataflair for more technologies and programming languages.

  4. madhav says:

    list=[]

    all(list)——output True

    any(list)——output False

    • DataFlair Team says:

      Hi Madhav
      Thanks for asking query, if you check the help for any and all, this is what you find:

      >>> help(all)

      Help on built-in function all in module builtins:

      all(iterable, /)
      Return True if bool(x) is True for all values x in the iterable.

      If the iterable is empty, return True.

      >>> help(any)
      Help on built-in function any in module builtins:

      any(iterable, /)
      Return True if bool(x) is True for any x in the iterable.

      If the iterable is empty, return False.

      This means that for an empty iterable, all() returns True and any() returns False. Hope, it helps!

  5. ilgaz says:

    Hello, I have a question regarding the third example of 6.b (Reassigning values to a list), I didn’t understand why 2:2 does not assign the ‘occur’ item to index 2. I mean, as I see the output should be the as follows:
    >>> colors[2:2] = [‘occur’]
    >>>colors
    Output : [‘caramel’, ‘gold’, ‘occur’, ‘silver’, ‘occur’]

    but as you stated the output becomes as [‘caramel’, ‘gold’, ‘occur’, ‘bronz’, ‘silver’]

    I don’t want to put ‘occur’ to index 2 and slide the other items to the right. I want to change the item at index 2 with ‘occur’.
    I understand that if I write colors[2] = [‘occur’] works as I wish but I don’t understand why colors[2:2] doesn not work the same way as colors[2].
    Thanks in advance.

  6. Ali haider says:

    What is the main types of lsit in python language.

    • DataFlair Team says:

      There are many types of list in python,below are few types of list in python
      1 Numeric List – [1, 2, 3, 4, 5, 6, 7, 8 ,9]
      2 String List – [‘orange’, ‘pineapple’, ‘mango’
      3 Boolean List – [True, False, False, False]
      4 Nested List – [2,3,4], [5,6,7], [8,9,10]
      5 Empty List – []

  7. Janmejaya says:

    Excellent Articulation of the concepts. Really helpful for beginners. Thanks for creating such a nice blog.

    • DataFlair Team says:

      We are glad that our readers are liking the Python List article. Stay with DataFlair for more learning!!!!

  8. khushi says:

    hii i am having trouble in writing the program of the following question

    write a menu driven program on list containing 5 operatios/aplications on list using user define function

    • DataFlair says:

      Hi Khushi,
      You can keep a select input and based on the value given by the user you can perform any one of the 5 operations on the list. I hope I could answer your question. If not, can you please give some more information like what operations you want to perform?

  9. Daniel says:

    Hi. First of all I want to thank you for writing all this, I’m a beginner so all this is super helpful. But I have a question regarding in the beginning, Python List examples.

    languages=[(‘English’,’Albanian’),’Gujarati’,’Hindi’,’Romanian’,’Spanish’]
    languages[0]
    Output (‘English’, ‘Romanian’)

    But I get the Output (‘English’, ‘Albanian’), I tried to run it in different ways, in the terminal and in the interactive window, with the same result. Am I doing something wrong?

    Best regards Daniel

    • DataFlair says:

      Yes, you are correct. The output should be (‘English’, ‘Albanian’). Thank you for finding the mistake and letting us know. We will make sure it is changed.

  10. Carl Watts says:

    You said of pop() that “It removes the element at the specified index, and prints it to the screen.”
    It doesn’t actually “print it to the screen”, it just removed the element from the list and returns it.
    Also, the common usage of pop() is to not supply an argument, in which case it removes and returns the last element of the list.

    • DataFlair says:

      You are correct, it returns the element removed. The pop() method removes the last element and returns it if there is no argument given to it. But in case if an argument is given to it, then it removed the value at the index in the list and returns that value.

Leave a Reply

Your email address will not be published. Required fields are marked *