Python Programming

Python List Operations, Built-In Functions, List Methods

Description:

Python list-this is a very detailed tutorial about the list in python and you will also learn what is the basic operation of the list…

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Python List Creating:

Lists are constructed using square brackets [ ] wherein you can include a list of items separated by commas. The syntax for creating list is, User defined Opening Bracket Closing Bracket Separated by Comma

>>> info = ["hi", "shahzada", "fawad", "programming", "digest"]
 >>> info

output:
[‘hi’, ‘shahzada’, ‘fawad’, ‘programming’, ‘digest’]

In each item in the Python List is a string. The contents of the Python List variable are displayed by executing the Python List variable name. When you print out the List, the output looks exactly like the list you had created. You can create an empty List without any items. The syntax is, list_name = [ ]

For example,

>>> number_list = [4, 4, 6, 7, 2, 9, 10, 15]
 >>> mixed_list = ['dog', 87.23, 65, [9, 1, 8, 1]]
>>> type(mixed_list)
<class 'list'>
 >>> empty_list = []
 >>> empty_list
>>> type(empty_list)
<class 'list'>

Here, number_list  contains items of the same type while in mixed_list  the items are a mix of type string, float, integer and another Python List itself. You can determine the type of a mixed_list variable by passing the variable name as an argument to type() function. the List type is called as list. An empty Python List can be created as shown in and the variable empty_list is of list type. You can store any item in a List like string, number, object, another variable and even another List. You can have a mix of different item types and these item types need not have to be homogeneous. For example, you can have a Python List which is a mix of type numbers, strings and another Python List itself.


Python List Basic Operations

In Python, lists can also be concatenated using the + sign, and the * operator is used to create a repeated sequence of List items. For example,

 >>> list_1 = [1, 3, 5, 7]
>>> list_2 = [2, 4, 6, 8]
>>> list_1 + list_2
[1, 3, 5, 7, 2, 4, 6, 8]
 >>> list_1 * 3
[1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]
 >>> list_1 == list_2
False

Two lists containing numbers as items are created. The list_1 and list_2 lists are added to form a new Python List. The new List has all items of both the lists. You can use the multiplication operator on the Python List. It repeats the items the number of times you specify and in the list_1 contents are repeated three times. Contents of the lists list_1 and list_2 are compared using the ==operator  and the result is Boolean False since the items in both the lists are different. You can check for the presence of an item in the List using in and not in membership operators. It returns a Boolean True or False. For example,



 >>> list_items = [1,3,5,7]
>>> 5 in list_items
True
>>> 10 in list_items
False

If an item is present in the Python List then using in operator results in True  else returns False Boolean value.

 

Python list() Function:

The built-in list() function is used to create a List. The syntax for list() function is, list([sequence]) where the sequence can be a string, tuple or list itself. If the optional sequence is not stated then an empty Python List is created. For example,

>>> quote = "How you doing?"
>>> string_to_list = list(quote)
>>> string_to_list
['H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']
 >>> friends = ["j", "o", "e", "y"]
>>> friends + quote
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
>>> friends + list(quote)
['j', 'o', 'e', 'y', 'H', 'o', 'w', ' ', 'y', 'o', 'u', ' ', 'd', 'o', 'i', 'n', 'g', '?']

The string variable quote  is converted to a list using the list() function. Now, let’s see whether a string can be concatenated with a Python List. The result is an Exception which says TypeError: can only concatenate list (not “str”) to list. That means you cannot concatenate a list with a string value. In order to concatenate a string with the List, you must convert the string value to list type, using Python built-in list() function.


Python List Indexing and Slicing:

As an ordered sequence of elements, each item in a Python List can be called apart, through indexing. The expression inside the bracket is called the index. Lists use square brackets [ ] to access individual items, with the first item at index 0, the second item at index 1, and so on. The index provided within the square brackets indicates the value being accessed. The syntax for accessing an item in a List is, list_name[index] where index should always be an integer value and indicates the item to be selected. For the list info, the index breakdown is shown below.

>>> info = ["hi", "shahzada", "fawad", "programming", "digest"]
>>> info[0]
'hi'
 >>> info[1]
'shahzada'
 >>> info [2]
'fawad'
>>> info [3]
'programming'
 >>> info [4]
'digest'
>>> info [9]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

The info  list has five items. To print the first item in the list use square brackets immediately after Python List name with an index value of zero. The index numbers for this info list range from 0 to 4. If the index value is more than the number of items in the Python List then it results in “IndexError: list index out of range” error. In addition to positive index numbers, you can also access items from the Python List with a negative index number, by counting backward from the end of the list, starting at −1. Negative indexing is useful if you have a long list and you want to locate an item towards the end of a Python List. For the same list info, the negative index breakdown is shown below.


>>> info[-3]
'fawad'

If you would like to print out the item ‘fawad’ by using its negative index number, you can do so as in.

 

 Modifying Items in Lists

Python Lists are mutable in nature as the list items can be modified after you have created a Python List. You can modify a list by replacing the older item with a newer item in its place and without assigning the list to a completely new variable. For example,

>>> fauna = ["pronghorn", "alligator", "bison"]
 >>> fauna[0] = "groundhog"
 >>> fauna
['groundhog', 'alligator', 'bison']
 >>> fauna[2] = "skunk"
>>> fauna
['groundhog', 'alligator', 'skunk']
 >>> fauna[-1] = "beaver"
 >>> fauna
['Groundhog', 'alligator', 'beaver']

You can change the string item at index 0 from ‘pronghorn’ to ‘groundhog’ as shown in. Now when you display fauna, the list items will be different. The item at index 2 is changed from “bison” to “skunk”. You can also change the value of an item by using a negative index number −1 which corresponds to the positive index number of  2. Now “skunk” is replaced with “beaver”. When you assign an existing Python List variable to a new variable, an assignment (=) on lists does not make a new copy. Instead, assignment makes both the variable names point to the same list in memory. For example,


>>> zoo = ["Lion", "Tiger", "Zebra"]
 >>> forest = zoo
>>> type(zoo)
<class 'list'>
 >>> type(forest)
<class 'list'>
 >>> forest
['Lion', 'Tiger', 'Zebra']
>>> zoo[0] = "Fox"
>>> zoo
['Fox', 'Tiger', 'Zebra']
 >>> forest
['Fox', 'Tiger', 'Zebra']
 >>> forest[1] = "Deer"
 >>> forest
['Fox', 'Deer', 'Zebra']
 >>> zoo
['Fox', 'Deer', 'Zebra']

The above code proves that assigning an existing list variable to a new variable does not create a new copy of the existing Python List items. Slicing of lists is allowed in Python wherein a part of the Python List can be extracted by specifying index range along with the colon (:) operator which itself is a list. The syntax for list slicing is,

where both start and stop are integer values (positive or negative values). Python List slicing returns a part of the list from the start index value to stop index value which includes the start index value but excludes the stop index value. Step specifies the increment value to slice by and it is optional. For the list fruits, the positive and negative index breakdown is shown below.

 >>> fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]
 >>> fruits[1:3]
['pineapple', 'blueberries']
>>> fruits[:3]
['grapefruit', 'pineapple', 'blueberries']
>>> fruits[2:]
['blueberries', 'mango', 'banana']
>>> fruits[1:4:2]
['pineapple', 'mango']
 >>> fruits[:]
['grapefruit', 'pineapple', 'blueberries', 'mango', 'banana']
>>> fruits[::2]
['grapefruit', 'blueberries', 'banana']
 >>> fruits[::-1]
['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']
 >>> fruits[-3:-1]
['blueberries', 'mango']



All the items in the fruits list starting from an index value of 1 up to index value of 3 but excluding the index value of 3 is sliced. If you want to access the start items, then there is no need to specify the index value of zero. You can skip the start index value and specify only the stop index value. Similarly, if you want to access the last stop items, then there is no need to specify the stop value and you have to mention only the start index value. When stop index value has skipped the range of items accessed extends up to the last item. If you skip both the start and

stop index values and specify only the colon operator within the brackets, then the entire items in the List are displayed. The number after the second colon tells Python that you would like to choose your slicing increment. By default, Python sets this increment to 1, but that number after second colon allows you to specify what you want it to be. Using double colon as shown in means no value for start index and no value for stop index and jump the items by two steps. Every second item of the list is extracted starting from an index value of zero. All

the items in a list can be displayed in reverse order by specifying a double colon followed by an index value of −1. Negative index values can also be used for start and stop index values.


Python list Built-In Functions:

There are many built-in functions of  list which are used in python which are given below:

len():

The len() function returns the numbers of items in a Python List.

sum():

The sum() function returns the sum of numbers in the Python List.

any():

The any() function returns True if any of the Boolean values in the Python List is True.

all():

The all() function returns True if all the Boolean values in the Python List are True, else

returns False.

sorted():

The sorted() function returns a modified copy of the Python List while leaving the original list untouched.


>>> lakes = ['superior', 'erie', 'huron', 'ontario', 'powell']
>>> len(lakes)

>>> numbers = [1, 2, 3, 4, 5]
>>> sum(numbers)
15
>>> max(numbers)
5
 >>> min(numbers)
1
 >>> any([1, 1, 0, 0, 1, 0])
True
>>> all([1, 1, 1, 1])
True
 >>> lakes_sorted_new = sorted(lakes)
>>> lakes_sorted_new
['erie', 'huron', 'ontario', 'powell', 'superior']

You can find the number of items in the list lakes using the len() function. Using the sum() function results in adding up all the numbers in the List. Maximum and minimum numbers in a Python List are returned using max() and min() functions. If any of the items is 1 in the list then any() function returns Boolean True value. If all the items in the list are 1 then all() function returns True else returns False Boolean value. The sorted() function returns the sorted list of items without modifying the original list which is assigned to a new list variable . In the case of string items in the list, they are sorted based on their ASCII values.


Python List Methods

The List size changes dynamically whenever you add or remove the items and there is no need for you to manage it yourself. You can get a list of all the methods associated with the list by passing the list function to dir().

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']

Various methods associated with list is displayed

Python List

Python List Methods Syntax and  Description:

append() list.append(item):

The append() method adds a single item to the end of the list. This method does not return new list and it just modifies the original.

count() list.count(item):

The count() method counts the number of times the item has occurred in the list and returns it.

insert() list.insert(index, item):

The insert() method inserts the item at the given index, shifting items to the right.

extend() list.extend(list2):

The extend() method adds the items in list2 to the end of the list.

index() list.index(item):

 The index() method searches for the given item from the start of the list and returns its index. If the value appears more than once, you will get the index of the first one. If the item is not present in the list then ValueError is thrown by this method.

remove() list.remove(item):

 The remove() method searches for the first instance of the given item in the list and removes it. If the item is not present in the list then ValueError is thrown by this method.

sort() list.sort():

The sort() method sorts the items in place in the list. This method modifies the original list and it does not return a new list.

reverse() list.reverse():

The reverse() method reverses the items in place in the list. This method modifies the original list and it does not return a new list.

pop() list.pop([index]):

The pop() method removes and returns the item at the given index. This method returns the rightmost item if the index is omitted.

Note: Replace the word “list” mentioned in the syntax with your actual list name in your code.


Example how to write Program to Display the Index Values of Items in List:

 silicon_valley = ["shahzada", "fawad", "programming", "digest"]
 for index_value in range(len(silicon_valley)):
 print(f"The index value of '{silicon_valley[index_value]}' is {index_value}")

Output
The index value of 'shahzada' is 0
The index value of 'fawad' is 1
The index value of 'programming' is 2
The index value of 'digest' is 3

You need to pass the list name as an argument to len() function and the resulting value will be passed as an argument to range() function to obtain the index value of each item in the list.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

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

Back to top button