Tuples and Lists

Tuples and Lists

Tuples and Lists these two are compound data types The major difference between these two is mutability ( Tuples are immutable like strings on the other hand Lists are mutable)

Tuples = ()

ordered sequence of element, can contain mix types

• Its a data type in python in which you can store multiple data types at once

• eg: t = (4, "hola", 2.9 ) (Tuple is a compound data type.)

• Like strings Tuples are immutable ( i.e we can't modify any index of it)

• i.e, if you try something like : t[0] + 1 this will give you a error

• Here index of tuples are the objects eg: t [0] = 4

• Just like string you can slice it using closed brackets eg: t [0, 2] = (4, "hola")

• You can concatenate tuples eg: m = ("sam", 3, ) then t + m will give a larger tuple i.e, (4, "hola", 2.9, "sam", 3, )

  • It can be really convenient to swap variable value

    eg: x = y and y = x this doesn't work

    temp = x
    x = y       this is the right way but `(x,y) = (y,x)` is better
    y = temp
    

Lists = [ ]

ordered sequence of information, accessible by index

  • Unlike Tuples and Strings Lists are mutable

• Lists are in square brackets eg:l = [33, "samueal" "jade" , 2.40]

• Because of its mutability we can do something like this : l[0] + 1 = m ; therefore m will be == 34 i.e, Unlike tuples, lists does not create a new object in memory it just mutates the existing object

  • Because of its mutable nature we can perform many operation over LISTs

Operations on LISTS - ADD

  • we can add elements to the end of the list with this operation as follows: eg:
    L = [ 2 , 1 , 3 ]
    L.append (5)    ---> This mutates L to L = [ 2 , 1 , 3 , 5 ]
    
    Note:- The dot between append and L can be considered as an operator for now

Operations on LISTS - ADD

  • We can combine two or more lists together using concatenation, i.e using the '+' operator this will give you a new list (will not mutate the existing list )
  • You can use operations like L.extend(any_list) eg:
    L1 = [2, 1, 3]
    L2 = [4, 0, 9]
    L3 = L1 + L2  <--- This doesn't mutate L1 and L2 
    while
    L.extend([4,6]) <--- This mutates the existing list L
    returns L = [ 2, 1 , 3 , 4 , 6 ]
    

Operations on LISTS - REMOVE

  • We can delete an element on any specific index from the list using del(L[index])
  • L.pop() removes the last element of the list and its very useful because it return the value it removed
  • You can remove a specific element from the from the list using L.remove(element)

Note:-

  • This will only delete the very first occurrence of that element from iterating left --> right and returns none
  • L.remove returns none value

Other List Operations

  • sort () and sorted ()
  • reverse()
    L = [ 9 , 6 , 0 , 3 ]
    sorted(L) ---> returns a sorted list , it does not mutate the list
    L.sort() ---> mutates the list itself ; here L = [ 0 , 3 , 6 , 9 ] 
    (It returns none value )
    L.reverse ---> mutates L= [ 9 , 6 , 3 , 0 ]
    

Converting Lists to Strings and back

  • To convert any String to List we can use list(s) <--- this returns every character of the string as a List element. ( Note:- here consider s as a string )
  • You can also split according to your own parameters using s.split ( if split is called without any parameter it splits on spaces )
  • To convert a list to string you can use ' ' . join(L) here you can put any character in quotes to put that character between every element. eg:
    s = "I<3 cs"           ---> s is a string
    list(s)         ---> returns [ 'I' , '<' ,'3' , ' ' , 'c' , 's' ]
    s.split('<')              ---> returns   [ 'I ',  '3 cs' ]
    L = [ 'a' , 'b' , 'c' ]  ---> L is a string
    ' ' . join(L)              ---> returns "abc"
    '_' . join(L)             ---> returns "a_b_c"
    

📌 Lists have side effects because of it's mutable nature which are described as follows:

Mutation, Aliasing, Cloning

  • We can assign many variable to the same object eg: attributes of a person: singer, blonde ---> Billie Eilish

all nicknames of Billie refer to the same person :

  • adding new attribute to any of them applies for every nickname Lil_avacado ---> singer, blonde, beautiful
  • all her old attributes refers to her every nickname + the new ones

Mammas ---> singer, blonde, beautiful

Cupcake ---> singer, blonde, beautiful

(NOTE: Blonde can vary sometimes 😅)

ALIASES

a = 1                                                                       
b = a                  
print(a)
print (b)

warm = [ 'red' , 'yellow' , 'orange'  ]
hot = warm 
hot.append('pink')
print(hot)
print(warm)

This gives the following result:

1
1
[ 'red' , 'yellow' , 'orange' , 'pink' ]
[ 'red' , 'yellow' , 'orange' , 'pink' ]

Screenshot 2022-09-12 at 11.46.38 PM.png

  • here hot is an alias for warm - changing one changes the other i.e append() has side effects

CLONING

  • To avoid the side effects by append we use cloning
  • We simply clone the LIST while assigning an alias to it. eg:
cool = [ 'blue' ,  'green ',  'grey' ]
chill = cool [ : ]        --->  [ : ] is used to clone the list
chill.append('black')
print(chill)
print(cool)

This gives us the following result:

[ 'blue' ,  'green ',  'grey' , 'black' ]
[ 'blue' ,  'green ',  'grey' ]

Screenshot 2022-09-13 at 10.48.25 AM.png

ITERATING

Iterating over Tuples:

  • Iterating over each element of Tuples is similar to iterating over each character of a string eg:
def get_data (aTuple):
    nums = ()
    words = ()
    for t in aTuple :
        nums += (t[0], )
        if t[1] not in words:
            words += (t[1], )
    min_n = min(nums)
    max_n = max(nums)
    unique_words = len(words)
    return(min_n, max_n, unique_words)        

print(get_data(((21,"sam"),(44, "cool"),(69, "oops"))))

This will give you the following result :

(21, 69, 3)

Iterating over Lists :

  • Because of the mutable nature of Lists there are some constraints like: avoid mutating list as you are iterating over it eg:
def remove_dups(L1, L2):
    for e in L1:
       if e in L2:
             L1.remove(e)

L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
print(L1)

This will print [ 2 , 3 , 4 ] instead of [ 3 , 4 ]

L1 is[ 2 , 3 , 4 ] not[ 3 , 4 ] Why? • Python uses an internal counter to keep track of index it is in the loop • mutating changes the list length but Python doesn’t update the counter • loop never sees element 2

Therefore we clone the LIST to avoid this : eg:

def remove_dups(L1, L2):
    L1_copy = L1[:]
    for e in L1_copy:
        if e in L2:
            L1.remove(e)

📌 If want to know more about Mutability and Immutability you can refer to the following article:

https://web.mit.edu/6.005/www/fa15/classes/09-immutability/

Did you find this article valuable?

Support Codexperiences by becoming a sponsor. Any amount is appreciated!