Tuple

5 flashcards · Programming Languages · by SubasriNatarajan

  1. >>>t=(1,2,4,3) >>>t[1:3] Guess the answer !

    (2, 4) Slicing in tuples takes place just as it does in strings.

  2. >>>t = (1, 2, 4, 3, 8, 9) >>>[t[i] for i in range(0, len(t), 2)] Guess the answer !

    [1, 4, 8]

  3. d = {"john":40, "peter":45} d["john"] Guess the answer !

    40

  4. >>>my_tuple = (1, 2, 3, 4) >>>my_tuple.append( (5, 6, 7) ) >>>print len(my_tuple) Guess the answer !

    Error Tuples are immutable and don’t have an append method. An exception is thrown in this case.

  5. numberGames = {} numberGames[(1,2,4)] = 8 numberGames[(4,2,1)] = 10 numberGames[(1,2)] = 12 sum = 0 for k in numberGames: sum += numberGames[k] print len(numberGames) + sum Guess the answer !

    33 Tuples can be used for keys into dictionary. The tuples can have mixed length and the order of the items in the tuple is considered when comparing the equality of the keys.