Python Lists Tutorial

Contents show

Python Lists Tutorial

Python list Tutorial
Python Lists Tutorial

Python Lists

A lists is a standard data type of Python that can store a sequence of values belonging to any type.

The Lists are depicted through square brackets, e.g., following are some Python Lists :

1. [ ] #list with no member, empty list
2. [1, 2, 3] #list of integers
3. [1, 2.5, 3.7, 9] #list of numbers (integers and floating point)
4. [‘a’, ‘b’, ‘c’,] #list of characters
5. [‘a’, 1, ‘b’, 3.5, ‘zero’] #list of mixed value types
6. [‘one’, ‘Two’, ‘Three’] #list of strings

Lists are mutable (i.e., modifiable) i.e., you can change elements of a list in place. List is one of the two mutable types of Python – Lists and Dictionaries are mutable types; all other data types of Python are immutable.

Creating Python Lists

To create a list, put a number of expressions, separated by commas in square brackets. That is, to create a list you can write in the form given below :

L = [ ]
L = [value, …]

This construct is known as a list display construct.

Creating Empty Python Lists

The empty list is [ ]. You can also create an empty list as :

L = list( ) #It will generate an empty list and name that list as L.

Creating Lists from Existing Sequences

You can also use the built-in list type object to create lists from sequences as per the syntax given below :

L = list(<sequence>)

where <sequence> can be any kind of sequence object including strings, tuples, and lists.

Consider following examples :

>>>l1 = list('hello')                   #creating list from string
['h', 'e', 'l', 'l', 'o']
>>>t = ('w', 'e', 'r', 't', 'y')
>>>12 = list(t)
['w', 'e', 'r', 't', 'y')

Creating List from keyboard Input

You can use this method of creating lists of single characters or single digits via keyboard input.

Consider the code below :

>>>l1 = list(input('Enter list elements:'))
Enter list elements: 234567
['2', '3', '4', '5', '6', '7']

Notice :-

this way the data types of all characters entered is string even though we entered digits. To enter a list of integers through keyboard, you can use the method given below :

list = eval(input("Enter list to be added :"))
Print("List you entered :", list)

when you execute it, it will work somewhat like :

Enter list to be added : [67,78, 46, 23]
List you entered : [67,78, 46, 23]

Lists vs. Strings

Python Lists

Lists and strings have lots in common yet key differences too. This section is going to summarize the similarties and differences between lists and strings.

(A) Similarity between Lists and Strings

Lists are similar to strings in following ways :

1. Length

Function len(L) returns the number of items(count) in the list L.

2. Indexing and Slicing

L[i] returns the item at index i (the first item has index 0), and L[i : j] returns a new list, containing the objects between i and j.

3. Membership operators

Both ‘in’ and ‘not in’ operator work on Lists just like they work for other sequences such as strings. (Operator in tells if an element is present in the list or not, and not in does the opposite.)

4. Concatenation and Replication operators + and *

The + operator adds one list to the end of another. The * operator repeats a list.

5. Accessing Individual Elements

Like strings, the individual elements of a list are accessed through their indexes.

Consider following examples :

>>> vowels = ['a', 'e', 'i', 'o', 'u']
>>> vowels[0]
>>> vowels[4]
>>> vowels[-1]
>>> vowels[-5]

(B) Difference between Lists and Strings

The lists and strings are different from one another in following ways :

1. Storage

Lists are stored in memory exactly like strings, except that because some of their objects are larger than others, they store a reference at each index instead of single character as in strings.

2. Mutability

Strings are not mutable, while lists are. You cannot change individual elements of a string in place, but Lists allow you to so. That is, following statement is fully valid for Lists (though not for strings) :

L[i] = <element>

For example, consider the same vowels list created above and have a look at following code :

>>> vowels[0] = 'A'
>>> vowels
['A', 'e', 'i', 'o', 'u']
>>> vowels[-4] = 'E'
>>> vowels
['A', 'E', 'i', 'o', 'u']

Notice :-

it changed the element in place; (‘a’ changed to ‘A’ and ‘e’ changed to ‘E’) no new List created – because List are MUTABLE.

List Operators

In this section, we shall talk about most common list operations, briefly.

1. Traversing a List

Traversing a list means accessing and processing each element of it. The for loop makes it easy to traverse or loo over the items in a list, as per following syntax :

for <item> in <List> :
      process each item here 

For example, following loop shows each item of a list L in separate lines :

L = ['P', 'y', 't', 'h', 'o', 'n']
for a in L :

The above loop will produce result as :


2. Joining Lists

The concatenation operator +, when used with two lists, joins two lists and returns the concatenation list. Consider the example given below :

>>> lst1 = [1, 4, 9]
>>> lst2 = [6, 12, 20]
>>> lst1 + lst2

The + operator when used with lists requires that both the operands must be of list types.

3. Repeating or Replicating Lists

Like strings, you can use * operator to replicate a list specified number of times, e.g., (considering the same list lst1 = [1, 4, 9])

>>> lst1 * 3
[1, 4, 9, 1, 4, 9, 1, 4, 9]

Like strings, you can only use an integer with a * operator when trying to replicate a list.

4. Slicing the Lists

List slices, like string slices are the sub part of a list extracted out. You can use indexes of list elements to create list slices as per following format :

seq = L[start : stop]

Consider the following example :

>>> lst = [10, 12, 14, 20, 22, 24, 30, 32, 34]
>>> seq = lst[3 : -3]
>>> seq
[20, 22, 24]
>>> lst = [10, 12, 14, 20, 22, 24, 30, 32, 34]
>>> lst[3 : 30]
[20, 22, 24, 30, 32, 34]
>> lst[-15 : 7]
[10, 12, 14, 20, 22, 24, 30]

lists also support slice steps too. That is, if you want to extract, not consecutive but every other element of the list, there is a way out – the slice steps. The slice steps are used as per following format :

seq = L[start : stop : step]

Consider some examples to understand this.

>>> lst 
[10, 12, 14, 20, 22, 24, 30, 32, 34]
>>> lst[0 : 10 : 2]
[10, 14, 22, 30, 34]
>>> lst[2 : 10 : 3]
[14, 24, 34]

Using slices for List Modification

You can use slices to overwrite one or more list elements with one or more other elements.
Following examples will make it clear to you :

>>> L = ["one", "two", "THREE"]
>>> L[0 : 2] = [0, 1]
>>> L
[0, 1, "THREE"]

>>> L = ["one", "two", "THREE"]
>>> L[0 : 2] = "a"
>>> L
["a", "THREE"]

Note :

Like strings, in list slices, you can give start and stop beyond limits of list and it won’t raise IndexError, rather it will retrn the elements failing between specified boundaries.

List Manipulation

You can perform various operations on lists like : appending, updating, deleting etc.

Appending Elements to a Python Lists

You can also add items to an existing sequence. The append( ) method adds a single items to the end of the list. It can done be done as per following format :


Consider some examples :

>>> lst1 = [10, 12, 14]
>>> lst1.append(16)
>>> lst1
[10, 12, 14, 16]          <-------- The element specified as argument to append( ) is added at the end of existing list

Updating Elements to a List

To update or change an element of the list in place, you just have to assign new value to the element’s index in list as per syntax :

L[index] = <new value>

Consider following example :

>>> lst1 = [10, 12, 14, 16]
>>> lst1[2] = 24
>>> lst1
[10, 12, 24, 16]

Deleting Elements from a List

You can also remove items from lists. The del statement can used to remove an individual item, or to remove all items identified by a slice.
It is to be used as per syntax given below :

del List[<index>]                     # to remove element at index
del List{<start> : <stop>]        # to remove elements in list slice


>>> del lst[10 : 15]         <---- Delete all elements between indexes 10 to 15 in list namely lst. compare the result  
                                                displayed below
>>> lst
[1,2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 18 , 19, 20]

If you use del<1stname> only e.g., del lst it will delete all the elements and the list object too.
After this, no object by the name 1st would be existing.

You can also use pop( ) method to remove single element, not list slices.
The pop( ) method is covered in later section, List Functions.

Making True Copy of a List

Python Lists

Assignment with an assignment operator (=) on lists not make a copy. Instead, assignment makes the two variables point to the one list in memory (called shallow copy).

colors = ['red', 'blue', 'green']
b = colors       # # Does not copy the list

So, if you make changes in one list, the other list will also report those changes because these two list-names are labels referring to same list because ‘=’ copied the reference not the actual list.

To make b true copy of list colors i.e., an independent list identical to list colors you should create copy of list as follows :

b = list(colors)

Now colors and b are separate lists (deep copy)

Python Lists Methods

Python also offers many built-in functions and methods for list manipulation. These can be applied to list as per following syntax :

<listobject>.<method name>( )

1. Python Lists index

This function returns the index of first matched item from the list.


For example, for a list L1 = [13, 18, 11, 16, 18, 14],

>>> L1.index(18)  <---- returns the index of first value 18, even if   
1                   there is another value 18 at index 4.

However, if the given item is not in the list, it raises exception value Error

2. The append method

The append( ) method adds an item to the end of the list. It works as per following syntax :

  • Takes exactly one element and returns no value

For example, to add a new item “yellow” to a list containing colours, you may write :

>>> colours = ['red', 'green', 'blue']
>>> colours.append('yellow')
>>> colours
['red', 'green', 'blue', 'yellow']

The append( ) does not return the new list, just modifies the original.

3. The extend method

The extend( ) method is also used for adding multiple elements(given in the form of a list) to a list. extend( ) function works as per following format :

  • Takes exactly one element (a list type) and returns no value

That is extend( ) takes a list as an argument and appends all of the elements of arguments list to the list object on which extend( ) is applied.

Consider the following example :

>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> t1
['a', 'b', 'c', 'd', 'e']
>>> t2
['d', 'e']

Difference between append( ) and extend( ) methods

While append( ) function add one element to a list, extend( ) can add multiple elements from a list supplied to it as argument.

4. The insert method

The insert( ) function inserts an item at a given position. It is used as per following syntax :

List.insert(<pos>, <item>)
  • Takes two arguments and returns no value.

The first argument is the index of the element before which the second argument is to be added.

Consider the following example :

>>> t1 = ['a', 'e', 'u']
>>> t1.insert(2, 'i')               # insert element 'i' at index 2.
>>> t1
['a', 'e', 'i', 'u']           # see element 'i' inserted at index 2

5. The pop method

The Pop( ) is used to remove the item from the list. It is used as per following syntax :

List.pop(<index>)                  # <index is optional argument
  • Takes one optional argument and returns a value – the item being deleted

Thus, pop( ) removes an element from the given position in the list, and return it. If no index is specified, pop( ) removes and returns the last item in the list.

Consider some examples :

>>> t1
['k', 'a', 'e', 'i', 'p', 'q', 'u']
>>> ele1 = t1.pop(0)
>>> ele1
'k'                    The removed element
>>> t1
['a', 'e', 'i', 'p', 'q', 'u'] <---list after removing first element
>>> ele2 = t1.pop( )  <--No index specified. it will remove the last element--->
>>> ele2
>>> t1
['a', 'e', 'i', 'p', 'q']        

The pop( ) method raises an exception (runtime error) if the list is already empty.

6. The remove method

The remove( ) method removes the first occurrence of given item from the list. It is used as per following format :

>>> t1 = ['a', 'e', 'i', 'p', 'q', 'a', 'q', 'p']
>>> t1.remove('a')
>>> t1
['e', 'i', 'p', 'q', 'a', 'q', 'p']    <--- First occurence of 'a' is removed from the list--->
>>> t1.remove('p')
>>> t1
['e', 'i', 'q', 'a', 'q', 'p']     <--- First occurence of 'p' is removed from the list--->

7. The clear method

This method removes all the items from the list and the list becomes empty list after this function. This function returns nothing. It is used as per following format.

List.clear( )

For instance, if you have list L1 as

>>> L1  = [2, 3, 4, 5]
>>> L1.clear( )      <----- it will remove all the items from list L1.
>>> L1
[ ]               <--- Now L1 is an empty list

Unlike del statement, clear( ) removes only the element and not the list element.
After clear( ), the list object still exists as an empty list.

8. The count method

This function returns the count of the item that you passed as argument. If the given item is not in the list, it return zero.
It is used as per following format :


for instance, for a list L1 = [13, 18, 20, 10, 18, 23]

>>> L1.count(18)
2     <----returns 2 as there are  two items with value 18 in list.
>>> L1.count(28)
0  <-----No item with value 28 in the list, hence it returned 0(zero)--->

9. The reverse method

The reverse( ) reverses the items of the list. This is done “in place”, i.e., it does not create a new list.
The syntax to use reverse method is :

List.reverse( )
  • Takes no argument, returns no list ; reverses the list ‘in place’ and does not return anything.

For example,

>>> t1 = ['e', 'i', 'q', 'a', 'q', 'p']
>>> t1.reverse( )
>>> t1             <--- the reverse list
['p', 'q', 'a', 'q', 'i', 'e']

10. The sort method

The sort( ) function sort the items of the list, by default in increasing order. This is done “in place”, i.e., it does not create a new list.
It is used as per following syntax :

List.sort( ) 
>>> t1 = ['e', 'i', 'q', 'a', 'q', 'p']
>>> t1.sort( )
>>> t1             <--- sorted list in default ascending order
['a', 'e', 'i', 'p', 'q', 'q']

Like reverse( ), sort( ) also performs its function and does not return anything.
To sort a list in decreasing order using sort( ), you can write :

>>> List.sort(reverse = True)

To

Python Lists programs practice questions

List Manipulation in python notes

Python Lists

FAQ Related Python Lists :-

Q 1. What are lists in Python?

ans. A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.

Each element or value that is inside of a list is called an item.

They enable you to keep data together that belongs together, condense your code, and perform the same methods and operations on multiple values at once.

Q 2. What is Python Lists with example?

ans. In Python programming, a list is created by placing all the items (elements) inside square brackets [] , separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc.).

list can also have another list as an item. This is called a nested list.

Q 3. Can you add lists in Python?

ans. It’s very easy to add elements to a List in Python programming. 

We can append an element at the end of the list, insert an element at the given index. 

We can also add a list to another listIf you want to concatenate multiple lists, then use the overloaded + operator.

python lists

Q 4. How do you compare two Python Lists?


Python sort() method and == operator to compare lists

We can club the Python sort() method with the == operator to compare two lists

Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

Q 5. Can a list contains another python list?


Python Lists

any() method

Another method is any() which we can use to check if the list contains any elements of another one.

Q 6. What does list () do in Python?

Ans. ListLists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Q 7. What are the features of python list?

Ans. The important characteristics of Python lists are as follows:

  • Python Lists are ordered.
  • Lists can contain any arbitrary objects.
  • List elements can be accessed by index.
  • Lists can be nested to arbitrary depth.
  • Lists are mutable.
  • Lists are dynamic.

Q 8. How does Python list work?

Ans. A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ] .

Python Lists Tutorial

Q 9. What does * List mean in Python?

Ans. It’s essentially a combination of tuple/list unpacking and *args iterable unpacking. Each iterable is getting unpacked on each iteration of the for loop.

Q 10. How do you create an empty python list?

Ans. This can be achieved by two ways i.e. either by using square brackets[] or using the list() constructor. Lists in Python can be created by just placing the sequence inside the square brackets [] . To declare an empty list just assign a variable with square brackets.

In this tutorial, you will learn python list completely and easily.

Python Lists video :-

video credit :- Telusko
Python Lists