Quick Contact

     

    Python List and Tuples
    What is list?

    A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we can modify its element after it created.

    Creating a list

    A list in Python can be declared by putting different comma-separated values between square brackets.

    Example:

    days = [‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’]; number = [1, 2, 3, 4, 5,6,7,8,9,0 ];

     

    chars = [“a”, “b”, “c”, “d”, “e”];

    
    
    Accessing elements from list

    Elements from the list can be accessed by using the square brackets for slicing along with the index to procure value available at that index of the list.

    Example:

    days [1]; number [1:6];

    
    
    Updating and Adding elements in lists

    We can update a single element or multiple elements of a list by giving the slice on the left-hand side of the assignment operator.

    Example:

    days [2] = ‘January’;

     

    We can add elements in the list by using the append () method.

    
    
    Deleting an element from list

    In Python, we can remove a list element by using the del statement if index is known of the element to be deleted.

    Example:

    del days [3];

    </pre

    Alternatively, we can use the remove () method to remove an element from a list. All of these list operations are demonstrated in the below example. First, we created the list. Next, we accessed the elements from the list. Then, we updated 3rd element in the list using the assignment operator. Lastly, we used the del statement to delete an element in the list, doing so days [2] has printed Wednesday as element which was present at days [2] index was deleted.

     

    Python List and Tuples

     

    Output

     

    Python List and Tuples

     

    Basic lists operations

     

    Like Python strings, we can use + and * operators on lists for operations like concatenation and repetition respectively.

     

    Following are the list operations on Python lists.

     

     

    Python Expression Results Description
    len([1, 2, 3, 4, 5]) 5 Length Operation.
    [1, 2, 3, 4, 5] + [6, 7, 8, 9, 0] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] Concatenation operation.
    [‘Hello’] * 3 [‘Hello’, ‘Hello’, ‘Hello’] Repetition operation.
    4 in [1, 2, 3, 4, 5] TRUE Membership operation.
    for a in [1, 2, 3, 4, 5]: print a, 1 2 3 4 5 Iteration operation.

     

    Indexing, Slicing, and Matrixes in Lists

     

    Python lists are nothing both sequences, therefore indexing and slicing work the same way for lists as they do for strings. Therefore, below operations are possible.

     

    Python List and Tuples

     

    In the above example, if index is negative then counting will start from the right side and if it starts with 0 then counting will be from left side. Like Python String, Python lists supports slicing and will print the sections of the lists as per their indexes.

     

    Built-in Lists Methods & Functions

     

    Following are Python built-in functions for List operations.

     

     

    Function Description
    cmp(list1, list2) This Python built-in function for lists compares elements of both lists.
    len(list) This Python built-in function for lists gives the total length of the list.
    max(list) This Python built-in function for lists returns item from the list with max value.
    min(list) This Python built-in function for lists returns item from the list with min value.
    list(seq) This Python built-in function for lists converts a tuple into list.

     

    What is Tuples?

     

    Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since the value of the items stored in the list can be changed, whereas the tuple is immutable, and the value of the items stored in the tuple cannot be changed.

     

    Creating a Tuple

     

    A tuple is a sequence of immutable Python objects. A tuple in Python can be declared by putting different comma-separated values between parentheses.

     

    Example

     

    days = (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’); number = (1, 2, 3, 4, 5,6,7,8,9,0 );

    chars = (“a”, “b”, “c”, “d”, “e”);

    Accessing elements from Tuples

    Elements from the tuple can be accessed by using the square brackets for slicing along with the index to procure value available at that index of the tuple.

    Example

    days [1]; number [1:6];

    
    
    Updating and Adding elements in Tuples

    We cannot modify any element of a tuple as tuples are immutable which means we cannot update or change the values or size of tuple elements.

    Deleting an element from Tuples

    It is not possible to remove an individual tuple element from a tuple as tuples are immutable. However, we can remove an entire tuple by just using the ‘del’ statement.

    All of these tuples operations are demonstrated in the below example. First, we created the tuples. Next, we accessed the elements from the tuples. We cannot update the value of any element in Tuple. Lastly, we used the ‘del’ statement to delete the entire tuple, when attempted to print the deleted tuple it throws an error as it no longer exists in memory.

    Python List and Tuples
    Basic Tuples operations

    Like Python strings, we can use + and * operators on tuples for operations like concatenation and repetition respectively.

    Following are the tuples operations on Python tuples.

    Python Expression Results Description
    len((1, 2, 3, 4, 5)) 5 Length operation
    (1, 2, 3, 4, 5)+ (6, 7, 8, 9, 0) (1, 2, 3, 4, 5, 6, 7, 8, 9, 0) Concatenation operation.
    (‘Hello’) * 3 (‘Hello’, ‘Hello’, ‘Hello’) Repetition operation
    4 in (1, 2, 3, 4, 5) TRUE Membership operation
    for a in (1, 2, 3, 4, 5): print a, 1 2 3 4 5 Iteration operation.
    Indexing, Slicing, and Matrixes in Tuples

    Python tuples are nothing but sequences, therefore indexing and slicing work the same way for tuples as they do for strings. Therefore, following operations are possible.

    Python List and Tuples

    In the above example, if index is negative then counting will start from right side. If it starts with 0 then counting will be from left side. Like Python String, Python tuples supports slicing and will print the sections of the tuples as per their indexes.

    Built-in Tuples Methods & Functions

    Following are Python built-in functions for Tuples operations.

    Function Description
    cmp(tuple1, tuple2) This Python built-in function for tuples compares elements of both tuples.
    len(tuple) This Python built-in function for tuples gives the total length of the tuple.
    max(tuple) This Python built-in function for tuples returns item from the tuple with max value.
    min(tuple) This Python built-in function for tuples returns item from the tuple with min value.
    tuple(seq) This Python built-in function for tuples converts a list into tuple.
    Negative Indexing

    The tuple element can also access by using negative indexing. The index of -1 denotes the rightmost element and -2 to the second last item and so on.

    The elements from left to right are traversed using the negative indexing.

    Deleting Tuple

    Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are immutable. To delete an entire tuple, we can use the del keyword with the tuple name.

    Example

    tuple1 = (1, 2, 3, 4, 5, 6)

     

    print(tuple1)

     

    del tuple1[0]

     

    print(tuple1)

     

    del tuple1

     

    print(tuple1)

    
    
    Output

    (1, 2, 3, 4, 5, 6)

     

    Traceback (most recent call last):

     

    File “tuple.py”, line 4, in < module>

     

    print(tuple1)

     

    NameError: name ‘tuple1’ is not defined

    
    
    Basic Tuple operations

    The operators like concatenation (+), repetition (*), Membership (in) works in the same way as they work with the list.

    Operators Description
    Repetition The repetition operator enables the tuple elements to be repeated multiple times.
    Concatenation It concatenates the tuple mentioned on either side of the operator.
    Membership It returns true if a particular item exists in the tuple otherwise false.
    Iteration The for loop is used to iterate over the tuple elements.
    Length It is used to get the length of the tuple.
    Where use tuple?

    Using tuple instead of list is used in the following scenario.

    1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be changed.
    2. Tuple can simulate a dictionary without keys. Consider the following nested structure, which can be used as a dictionary.

    [(101, “Ron”, 10), (102, “Bob”, 20), (103, “George”, 40)]

    Reversing Elements

    Reverse elements within a tuple

     

    colors = “red”, “green”, “blue” rev = colors[::-1]

     

    # rev: (“blue”, “green”, “red”)

     

    colors = rev # colors: (“blue”, “green”, “red”)

     

    Or using reversed (reversed gives an iterable which is converted to a tuple):

     

    rev = tuple(reversed(colors))

     

    # rev: (“blue”, “green”, “red”) colors = rev

     

    # colors: (“blue”, “green”, “red”)

    Enroll Yourself: Python Training

    
    
    							
    	                        
    
    	                    

    Copyright 1999- Ducat Creative, All rights reserved.