Python List

Here, we have learnt about what is python list, creating list, adding and accessing elements in python list and also about python list methods and...

In this article we will going to discuss about what is python list, creating list, adding and accessing elements in python list and also about python list methods and list comprehension python.

Python List

What is Python List?

Python list is a data type which allows us to work with various elements at a time. In python list, the sequence of different types of data are stored. Python list is a similar to dynamically sized arrays that is written in different language. Simply, we can say that the list contains the collection of different types of items, values, etc. A list may contain integers, objects, strings, etc. And the elements or items of a list can be different type. In the list, the items are separated by the comma (,) and these are written within the square brackets .

Python list are mutable which means that the list can be altered even after their creation. And we can access the items/elements is a list by index.

Creating a Python List

In python, we can create a list by just writting the elements or items within the square brackets and the items are separated by the conmas (,).

# Python list of integers
li = [1, 2, 3]

A python list may contain strings, integers, floats, objects, etc. 

# Python empty list

li = []

# Python mixed data types list

li = [7, "Answersjet", 8.4]

And we can also create a python nested list which means a list that contains another list within it. 

 # Python nested list
li = ["Answersjet", [14, 2, 7], ['x']]

Adding elements to Python List

As we know, Python list are mutable which means that the list can be altered even after their creation. Python allows us to add elements by using three built-in functions which are explained as follows;

append() function

In Python list, we can add elements by using the built-in function. With append() function we can add elements at the the end of list one by one. And if we can use loops, if we want to add multiple elements using method.

li = list([14, 9, 'Answersjet', 7.5])

# Using Python append()

li.append('deepak thakur')

print(li)

# Python append nested list at the end

li.append([15, 5, 95])

print(li)

Output

[14, 9, 'Answersjet', 7.5, 'deepak thakur']
[14, 9, 'Answersjet', 7.5, 'deepak thakur', [15, 5, 95]]

insert() function

In Python list, to add elements in desired position the function is used. The function uses two arguments unlike the function.

li = list([14, 9, 'Answersjet', 7.5])

# Using insert()

li.insert(2, 22)

print(li)

# python insert nested list

li.insert(7, [1, 12, 79])

print(li)

Output

[14, 9, 22, 'Answersjet', 7.5]
[14, 9, 22, 'Answersjet', 7.5, [1, 12, 79]]

extend() function

To add multiple elements in the python list, the function is used. But by using function we can only add elements in the end of the list.

li = list([14, 9, 'Answersjet', 7.5])

# Using python extend()

li.extend([10, 15, 69])

print(li)

Output

[14, 9, 'Answersjet', 7.5, 10, 15, 69]

Accessing Python List elements

In python, we can access the elements in a list in the following ways;

List Index

The index operator is used to access an element from a list. The python indexes starts from 0 which means if we have a list of 5 items then the index will be from 0 to 4. And only integer are used in index, if we use float or other objects then it will result into . And if you want to access a nested list then the nested indexing is used.

li = ['d', 'e', 'p', 'a', 'k']

# first item of list

print(li[0])  

# third item of list

print(li[2])  

# fifth item of list

print(li[4]) 

# python Nested List

n_li = ['Answersjet', [1, 9, 0, 7]]

# python Nested indexing lists

print(n_li[0][1])

print(n_li[1][3])

# Error!

print(li[4.0])

Output

d

p

k

n

7

Traceback (most recent call last):

  File "<string>", line 14, in <module>

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

Negative Indexing

In Python, we can also perform negative indexing for the sequences of list. In the negative indexing, the last item is represented by the index -1 and the second item is represented by the index -2 and so on.

# Negative indexing in python lists

li = ['d','e','p','a','k']

# second last item

print(li[-2])

# fifth last item

print(li[-5])

Output

a
d

Deleting Python List elements

In python, we can delete a whole list by using the Python delete statement.

# Deleting python list items

li = ['a', 'n', 's', 'w', 'e', 'r', 's', 'j', 'e', 't']

# delete one item

del li[4]

print(li)

# delete multiple Python list items

del li[1:7]

print(li)

# delete the entire python list

del li

# Error!

print(li)

Output

['a', 'n', 's', 'w', 'r', 's', 'j', 'e', 't']

['a', 'e', 't']

Traceback (most recent call last):

  File "<string>", line 12, in <module>

NameError: name 'li' is not defined

But in order to delete the elements from the list then there are following two ways;

remove() function

Python allows us to delete the elements of list by using the built-in function. The remove method delete only a specified item at a time.

li = list([2, 4, 7, 8, 12, 14])

# remove item 2

li.remove(2)

# remove item 14

li.remove(14)

print(li)

Output

[4, 7, 8, 12]

pop() function

The built-in function also removes the elements of a list but it removes the last item of the list if you didn't provide the index.

li = list([2, 6, 9, 14, 16, 12])

li.pop(1)

print(li)

# remove python list item without passing index number

li.pop()

print(li)

Output

[2, 9, 14, 16, 12]
[2, 9, 14, 16]

Python List Slicing

In python, slicing operation is used to access or print a specific range of elements in the list. To perform the slice operation in the python list a colon is used.

# Python list slicing

li = ['a','n','s','w','e','r','s','j','e', 't']

# elements from index 4 to 5

print(li[4:6])

# elements from index 6 to end

print(li[6:])

print(li[:])

Output

['e', 'r']
['s', 'j', 'e', 't']
['a', 'n', 's', 'w', 'e', 'r', 's', 'j', 'e', 't']

Python List Comprehension

Python list comprehension allows us to create a new list in a concise and elegant way from other list or iterables like tuple, arrays, etc. In List comprehension python, the expression followed by the for or if statement is written inside the square brackets . The use of for and if statement is optional.

odd = []

for x in range(1, 17):

    if x % 2 == 1:

        odd.append(x**3)

print(odd)

Output

[1, 27, 125, 343, 729, 1331, 2197, 3375]

Python List Methods

The python list methods are discussed in the following table;

S.No Method Description
1. append() To add an element in the end of a list.
2. clear() To remove all the elements from a list.
3. count() The count of numbers of elements passed as an argument are returned by using this function.
4.copy() The copy of a list is returned using this function.
5. extend() To add multiple elements in the end of a list.
6. index() The index of first matched elements returned using this function.
7. insert() To insert an element at a defined position.
8.pop() To remove and return an element at the provided index.
9. reverse() The order of list is reversed using this function.
10. sort() Python sort list function is used to sort elements in ascending order of a list.
11. remove() To remove an element from a the list.

Built-in function in Python list

The built-in functions in the python list explained in the following table;

S.No Function Description
1. all() If the list is empty or all the elements of list are true then it returns true.
2. any() If the list is empty then it returns false and if any element of the list is true then it returns true.
3. accumulate() Returns a list of intermediate results after applying a particular function to all elements of a list.
4.ord() To return the integer with unicode code of a specified Unicode Character.
5. enumerate() To return the enumerate object of a list.
6. filter() To test whether the elements of the list are true or not.
7. lambda() This function have only one expression and numbers of arguments.
8.len() To return the length or size of the list.
9. max() To return maximum elements from a list.
10. min() To return minimum elements from a list.
11. map() After applying the specified functions to each item of a given iterable, this function returns a result's list.
12.reduce() Returns the final summation value after storing the intermediate result.
13.sum() To sum up the number of the list.
14.cmp() If the first list is greater than the second list this function returns 1.

Conclusion

From above we have learnt about what is python list, creating list, adding and accessing elements in python list and also about python list methods and list comprehension python. Python list is a data type which allows us to work with various elements at a time. In python list, the sequence of different types of data are stored.