***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***
***Use tabs for Content***

POSTS

    Copying Lists

    To make a copy of a list, you must copy the list’s elements.

    # Create a list.

    list1 = [1, 2, 3, 4]

    # Assign the list to the list2 variable.

    list2 = list1

    After this code executes, both variables list1 and list2 will reference the same list in memory.


    Changing an element in one list also effects another list because both reference same list in memory.

    >>> list1[0] = 99

    >>> print(list1)

    [99, 2, 3, 4]

     >>> print(list2)

     [99, 2, 3, 4]

    Suppose you wish to make a copy of the list, so that list1 and list2 reference two separate but identical lists. One way to do this is with a loop that copies each element of the list.

    Example:

    # Create a list with values.

    list1 = [1, 2, 3, 4]

    # Create an empty list.

    list2 = []

    # Copy the elements of list1 to list2.

    for item in list1:

    list2.append(item)