Python List Operations, Built-In Functions, List Methods

Python List

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…

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

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,

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,

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,

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,

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.

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.

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,

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,

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.


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.


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().

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:

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.


Related Article:

Python Regular Expressions or regex Matching, Searching, Replacing

 

 

 

Recommended For You

Leave a Reply

%d bloggers like this: