Python- Lists

Python Lists


        mylist = ["apple", "banana", "cherry"]


List


Lists are used to save more than one objects in a single variable.

Lists are one of four built-in statistics kinds in Python used to save collections of data, the different three are Tuple, Set, and Dictionary, all with distinct traits and usage.

Lists are created the usage of rectangular brackets:


Example:-


        Create a List:

        thislist = ["apple", "banana", "cherry"]
        print(thislist)

                               Try it Yourself»»

List Items


List gadgets are ordered, changeable, and enable replica values.

List objects are indexed, the first object has index [0], the 2d object has index [1] etc.


Ordered


When we say that lists are ordered, it capacity that the objects have a described order, and that order will now not change.

If you add new objects to a list, the new gadgets will be positioned at the give up of the list.


Note: There are some listing strategies that will alternate the order, however in general: the order of the objects will no longer change.

Changeable


The listing is changeable, that means that we can change, add, and do away with gadgets in a listing after it has been created.

Allow Duplicates


Since lists are indexed, lists can have objects with the equal value:

Example:-

        Lists permit reproduction values:

        thislist = ["apple", "banana", "cherry", "apple", "cherry"]
        print(thislist)

                            Try it Yourself»»



List Length


To decide how many objects a listing has, use the len( ) function:

Example:-

        Print the wide variety of objects in the list:

        thislist = ["apple", "banana", "cherry"]
        print(len(thislist))


                            Try it Yourself»»

List Items - Data Types



List gadgets can be of any facts type:

Example:-


        String, int and boolean information types:

        list1 = ["apple", "banana", "cherry"]
        list2 = [1, 5, 7, 9, 3]
        list3 = [True, False, False]

                            Try it Yourself»»

A listing can incorporate special statistics types:

Example:-

        A listing with strings, integers and boolean values:

        list1 = ["abc", 34, True, 40, "male"]

                            Try it Yourself»»

type( )

From Python's perspective, lists are described as objects with the records kind 'list':

Example:-


        What is the statistics kind of a list?

        mylist = ["apple", "banana", "cherry"]
        print(type(mylist))

                            Try it Yourself»»


The list( ) Constructor


It is additionally viable to use the list( ) constructor when developing a new list.

Example:-

        Using the list( ) constructor to make a List:

        thislist = list(("apple", "banana", "cherry"))     # notice the double round-brackets
        print(thislist)

                             Try it Yourself»»

Python Collections (Arrays)

There are 4 series records sorts in the Python programming language:

  • List is a series which is ordered and changeable. Allows replica members.
  • Tuple is a series which is ordered and unchangeable. Allows replicamembers.
  • Set is a series which is unordered and un-indexed. No reproduction members.
  • Dictionary is a series which is ordered* and changeable. No replica members.


*As of Python model 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When selecting a series type, it is beneficial to recognize the houses of that type. Choosing the proper kind for a precise facts set should suggest retention of meaning, and, it may want to suggest an expand in efficiency or security.


Python - Access List Items


Access Items

List objects are listed and you can get right of entry to them by means of referring to the index number:

Example:-

        Print the 2nd object of the list:

        thislist = ["apple", "banana", "cherry"]
        print(thislist[1])

                               Try it Yourself»»

Negative Indexing


Negative indexing skill begin from the end 

-1 refers to the ultimate item, -2 refers to the 2nd closing object etc.

Example:-

        Print the ultimate object of the list:

        thislist = ["apple", "banana", "cherry"]
        print(thislist[-1])

                    

                            Try it Yourself»»

Range of Indexes

You can specify a vary of indexes by using specifying the place to begin and the place to cease the range.

When specifying a range, the return cost will be a new listing with the detailed items.

Example:-

        Return the third, fourth, and fifth item:

        thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
        print(thislist[2:5])

                            Try it Yourself»»


Note: The search will begin at index two (included) and cease at index 5 (not included).


Remember that the first object has index 0.


By leaving out the begin value, the vary will begin at the first item:


Example:-

        This instance returns the gadgets from the commencing to, however NOT including, "kiwi":
        thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
        print(thislist[:4])

                            Try it Yourself»»


By leaving out the cease value, the vary will go on to the stop of the list:

Example:-

        This instance returns the gadgets from "cherry" to the end:

        thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
        print(thislist[2:])

                           Try it Yourself»»


Range of Negative Indexes

Specify bad indexes if you choose to begin the search from the stop of the list:

Example:-

        This instance returns the objects from "orange" (-4) to, however NOT which include "mango" (-1):

        thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
        print(thislist[-4:-1])

                                Try it Yourself»»


Check if Item Exists


To decide if a targeted object is existing in a listing use the in keyword:

Example:-

        Check if "apple" is current in the list:

        thislist = ["apple", "banana", "cherry"]
        if "apple" in thislist:
            print("Yes, 'apple' is in the fruits list")

                       Try it Yourself»»


Python - Change List Items


Change Item Value

To exchange the fee of a particular item, refer to the index number:

Example:-

        Change the 2d item:
        thislist = ["apple", "banana", "cherry"]
        thislist[1] = "blackcurrant"
        print(thislist)

                            Try it Yourself»»


Change a Range of Item Values

To alternate the cost of gadgets inside a precise range, outline a listing with the new values, and refer to the vary of index numbers the place you favor to insert the new values:

Example:-

        Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":

        thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
        thislist[1:3] = ["blackcurrant", "watermelon"]
        print(thislist)

                            Try it Yourself»» 


If you insert extra gadgets than you replace, the new objects will be inserted the place you specified, and the last gadgets will cross accordingly:

Example:-

        Change the 2d cost through changing it with two new values:

        thislist = ["apple", "banana", "cherry"]
        thislist[1:2] = ["blackcurrant", "watermelon"]
        print(thislist)

                            Try it Yourself»»


Note: The size of the listing will exchange when the wide variety of objects inserted does now not in shape the quantity of objects replaced.

If you insert much less gadgets than you replace, the new objects will be inserted the place you specified, and the final gadgets will go accordingly:

Example:-

        Change the 2nd and 1/3 fee through changing it with one value:

        thislist = ["apple", "banana", "cherry"]
        thislist[1:3] = ["watermelon"]
        print(thislist)

                            Try it Yourself»»

Insert Items

To insert a new listing item, besides changing any of the current values, we can use the insert( ) method.


The
insert( ) approach inserts an object at the precise index:

Example:-

        Insert "watermelon" as the 1/3 item:

        thislist = ["apple", "banana", "cherry"]
        thislist.insert(2, "watermelon")
        print(thislist)

                            Try it Yourself»»


Python - Add List Items


Append Items

To add an object to the quit of the list, use the append( ) method:

Example:-

        Using the append( ) technique to append an item:

        thislist = ["apple", "banana", "cherry"]
        thislist.append("orange")
        print(thislist)

                            Try it Yourself»»

Insert Items

To insert a listing object at a precise index, use the insert( ) method.

The insert( ) technique inserts an object at the specific index:

Example:-

        Insert an object as the 2nd position:

        thislist = ["apple", "banana", "cherry"]
        thislist.insert(1, "orange")
        print(thislist)

                            Try it Yourself»»


Extend List

To append factors from every other listing to the modern list, use the extend( ) method.

Example:-

        Add the factors of tropical to thislist:

        thislist = ["apple", "banana", "cherry"]
        tropical = ["mango", "pineapple", "papaya"]
        thislist.extend(tropical)
        print(thislist)

                            Try it Yourself»»


The factors will be brought to the give up of the list.

Add Any Iterable

The extend( ) approach does no longer have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).

Example:-

        Add factors of a tuple to a list:
        thislist = ["apple", "banana", "cherry"]
        thistuple = ("kiwi", "orange")
        thislist.extend(thistuple)
        print(thislist)

                            Try it Yourself»»


Python - Remove List Items


Remove Specified Item

The remove( ) approach gets rid of the certain item.

Example:-

        Remove "banana":

        thislist = ["apple", "banana", "cherry"]
        thislist.remove("banana")
        print(thislist)

                            Try it Yourself»»


Remove Specified Index

The pop( ) approach eliminates the distinct index.

Example:-

        Remove the 2nd item:

        thislist = ["apple", "banana", "cherry"]
        thislist.pop(1)
        print(thislist)

                            Try it Yourself»»


If you do now not specify the index, the pop( ) approach eliminates the final item.

Example:-

        Remove the ultimate item:

        thislist = ["apple", "banana", "cherry"]
        thislist.pop( )
        print(thislist)

                            Try it Yourself»»


The del key-word additionally eliminates the designated index:

Example:-

        Remove the first item:

        thislist = ["apple", "banana", "cherry"]
        del thislist[0]
        print(thislist)

                            Try it Yourself»»


The del key-word can additionally delete the listing completely.

Example:-

        Delete the complete list:

        thislist = ["apple", "banana", "cherry"]
        del thislist

                            Try it Yourself»»


Clear the List

The clear( ) approach empties the list.

The listing nevertheless remains, however it has no content.

Example:-

        Clear the listing content:

        thislist = ["apple", "banana", "cherry"]
        thislist.clear()
        print(thislist)

                            Try it Yourself»»


Python - Loop Lists


Loop Through a List

You can loop thru the listing gadgets via the use of a for loop:

Example:-

        Print all objects in the list, one by using one:

        thislist = ["apple", "banana", "cherry"]
        for x in thislist:
        print(x)

                            Try it Yourself»»


Loop Through the Index Numbers

You can additionally loop via the listing gadgets by way of referring to their index number.

Use the range( ) and len( ) features to create a appropriate iterable.

Example:-

        Print all objects via referring to their index number:

        thislist = ["apple", "banana", "cherry"]
        for i in range(len(thislist)):
        print(thislist[i])

                            Try it Yourself»»


The iterable created in the example above is [0, 1, 2].


Using a While Loop

You can loop via the listing objects by means of the usage of a while loop.

Use the len( ) characteristic to decide the size of the list, then begin at zero and loop your way thru the listing gadgets through refering to their indexes.

Remember to enlarge the index by using 1 after every iteration.

Example:-

        Print all items, the use of a whilst loop to go thru all the index numbers:

        thislist = ["apple", "banana", "cherry"]
        i = 0
        while i < len(thislist):
        print(thislist[i])
        i = i + 1

                            Try it Yourself»»


Looping Using List Comprehension

List Comprehension presents the shortest syntax for looping via lists:

Example:-

        A brief hand for loop that will print all objects in a list:

        thislist = ["apple", "banana", "cherry"]
        [print(x) for x in thislist]

                            Try it Yourself»»


Python - List Comprehension

List Comprehension

List comprehension presents a shorter syntax when you prefer to create a new listing based totally on the values of an present list.

Example:-

Based on a listing of fruits, you desire a new list, containing solely the fruits with the letter "a" in the name.

Without listing comprehension you will have to write a for assertion with a conditional take a look at inside:

Example:-

        fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
        newlist = [ ]

        for x in fruits:
            if "a" in x:
                newlist.append(x)

        print(newlist)

                            Try it Yourself»»


With listing comprehension you can do all that with solely one line of code:

Example:-

        fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

        newlist = [x for x in fruits if "a" in x]

        print(newlist)

                            Try it Yourself»»


The Syntax

        newlist = [expression for object in iterable if situation == True]

The return cost is a new list, leaving the historical listing unchanged.

Condition

The circumstance is like a filter that solely accepts the objects that valuate to True.

Example:-

        Only receive gadgets that are no longer "apple":

        newlist = [x for x in fruits if x != "apple"]

                            Try it Yourself»»


The situation if x != "apple" will return True for all factors different than "apple", making the new listing include all fruits besides "apple".

The condition is optionally available and can be omitted:

Example:-

        With no if statement:

        newlist = [x for x in fruits]

                            Try it Yourself»»


Iterable

The iterable can be any iterable object, like a list, tuple, set etc.

Example:-

        You can use the range( ) characteristic to create an iterable:

        newlist = [x for x in range(10)]

                            Try it Yourself»»


Same example, however with a condition:

Example:-

        Accept solely numbers decrease than 5:

        newlist = [x for x in range(10) if x < 5]


Expression

The expression is the contemporary object in the iteration, however it is additionally the outcome, which you can manipulate earlier than it ends up like a listing object in the new list:

Example:-

        Set the values in the new listing to top case:

        newlist = [x.upper() for x in fruits]

                            Try it Yourself»»

You can set the effect to anything you like:

Example:-

        Set all values in the new listing to 'hello':

        newlist = ['hello' for x in fruits]

                            Try it Yourself»»


The expression can additionally include conditions, now not like a filter, however as a way to manipulate the outcome:

Example:-

        Return "orange" as an alternative of "banana":

        newlist = [x if x != "banana" else "orange" for x in fruits]

                            Try it Yourself»»

The expression in the instance above says:

"Return the object if it is no longer banana, if it is banana return orange".


Python - Sort Lists


Sort List Alphanumerically

List objects have a sort( ) approach that will kind the listing alphanumerically, ascending, via default:

Example:-

        Sort the listing alphabetically:

        thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
        thislist.sort()
        print(thislist)

                            Try it Yourself»»


Example:-

        Sort the listing numerically:

        thislist = [100, 50, 65, 82, 23]
        thislist.sort()
        print(thislist)

                            Try it Yourself»»


Sort Descending

To type descending, use the key-word argument reverse = True:

Example:-

        Sort the listing descending:

        thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
        thislist.sort(reverse = True)
        print(thislist)

                            Try it Yourself»»


Example:-

        Sort the listing descending:

        thislist = [100, 50, 65, 82, 23]
        thislist.sort(reverse = True)
        print(thislist)

                            Try it Yourself»»


Customize Sort Function

You can additionally personalize your very own feature by using the usage of the key-word argument key = function.

The feature will return a quantity that will be used to type the listing (the lowest quantity first):

Example:-

Sort the listing based totally on how shut the variety is to 50:

        def myfunc(n):
            return abs(n - 50)

        thislist = [100, 50, 65, 82, 23]
        thislist.sort(key = myfunc)
        print(thislist)

                            Try it Yourself»»


Case Insensitive Sort

By default the sort( ) approach is case sensitive, ensuing in all capital letters being sorted earlier than decrease case letters:

Example:-

        Case touchy sorting can supply an surprising result:

        thislist = ["banana", "Orange", "Kiwi", "cherry"]
        thislist.sort()
        print(thislist)

                            Try it Yourself»»

Luckily we can use built-in features as key features when sorting a list.

So if you desire a case-insensitive type function, use str.lower as a key function:

Example:-

        Perform a case-insensitive kind of the list:

        thislist = ["banana", "Orange", "Kiwi", "cherry"]
        thislist.sort(key = str.lower)
        print(thislist)

                            Try it Yourself»»


Reverse Order

What if you prefer to reverse the order of a list, regardless of the alphabet?

The reverse( ) technique reverses the present day sorting order of the elements.

Example:-

        Reverse the order of the listing items:

        thislist = ["banana", "Orange", "Kiwi", "cherry"]
        thislist.reverse( )
        print(thislist)

                            Try it Yourself»»

Python - Copy Lists

Copy a List

You can't reproduction a listing truely by way of typing list2 = list1, because: list2 will solely be a reference to list1, and adjustments made in list1 will mechanically additionally be made in list2.

There are approaches to make a copy, one way is to use the built-in List approach copy( ).

Example:-

        Make a replica of a listing with the copy() method:

        thislist = ["apple", "banana", "cherry"]
        mylist = thislist.copy()
        print(mylist)

                            Try it Yourself»»


Another way to make a replica is to use the built-in approach list( ).

Example:-

        Make a reproduction of a listing with the list() method:

        thislist = ["apple", "banana", "cherry"]
        mylist = list(thislist)
        print(mylist)

                            Try it Yourself»»


Python - Join Lists

Join Two Lists

There are numerous methods to join, or concatenate, two or extra lists in Python.
One of the best approaches are by way of the usage of the + operator.

Example:-

        Join two list:

        list1 = ["a", "b", "c"]
        list2 = [1, 2, 3]

        list3 = list1 + list2
        print(list3)

                            Try it Yourself»»


Another way to be part of two lists is with the aid of appending all the gadgets from list2 into list1, one with the aid of one:

Example:-

        Append list2 into list1:

        list1 = ["a", "b" , "c"]
        list2 = [1, 2, 3]

        for x in list2:
            list1.append(x)

        print(list1)

                            Try it Yourself»»


Or you can use the extend( ) method, which reason is to add factors from one listing to some other list:

Example:-

        Use the extend( ) technique to add list2 at the quit of list1:

        list1 = ["a", "b" , "c"]
        list2 = [1, 2, 3]

        list1.extend(list2)
        print(list1)

                            Try it Yourself»»

Python - List Methods

List Methods

Python has a set of built-in strategies that you can use on lists.

   Method          Description

        append( )           Adds an aspect at the stop of the list.

        clear( )               Removes all the factors from the list.

        copy( )               Returns a reproduction of the list.

        count( )              Returns the quantity of factors with the distinctive value.

        extend( )            Add the factors of a listing (or any iterable), to the give up of the present day list.

        index( )              Returns the index of the first issue with the certain value.

        insert( )              Adds an component at the detailed position.

        pop( )                 Removes the thing at the distinctive position.

        remove( )           Removes the object with the particular value.

        reverse( )           Reverses the order of the list.

        sort( )                Sorts the list.


Post a Comment

0 Comments