Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Create a Python Tuple of Size n?
1
How to Create a Python Tuple of Size n?

5/5 – (1 vote)

Use the tuple concatenation operation
Code:
*
with a tuple with one element
Code:
(42,)
as a right operand and the number of repetitions of this element as a left operand. For example, the expression
Code:
(42,) * n
creates the tuple
Code:
(42, 42, 42, 42, 42)
for
Code:
n=5
.

Let’s play with an interactive code shell before you’ll dive into the detailed solution!

https://trinket.io/embed/python/2f2185e99e

Exercise: Initialize the tuple with
Code:
n=20
placeholder elements
Code:
-1
and run the code.


Problem Formulation

Next, you’ll learn about the more formal problem and dive into the step-by-step solution.

Problem: Given an integer
Code:
n
. How to initialize a tuple with
Code:
n
placeholder elements (e.g.,
Code:
42
)?

Code:
# n=0 --> () # n=1 --> (42,) # n=5 --> (42, 42, 42, 42, 42)
Example 1 – Tuple Concatenation

Use the tuple concatenation operation
Code:
*
with a tuple with one element
Code:
(42,)
as right operand and the number of repetitions of this element as left operand. For example, the expression
Code:
(42,) * n
creates the tuple
Code:
(42, 42, 42, 42, 42)
for
Code:
n=5
.

Code:
n = 5 t = (42,) * n print(t) # (42, 42, 42, 42, 42)

Note that you cannot change the values of a tuple, once created, because unlike lists tuples are immutable. For example, trying to overwrite the third tuple value will yield a
Code:
TypeError: 'tuple' object does not support item assignment
.

Code:
>>> x = (42,) * 5 >>> x[0] = 'Alice' Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> x[0] = 'Alice' TypeError: 'tuple' object does not support item assignment
Example 2 – N-Ary Tuple Concatenation

You can also use a generalization of the unary tuple concatenation — I call it n-ary tuple concatenation — to create a tuple of size
Code:
n
. For example, given a tuple
Code:
t
of size 3, you can create a tuple of size 9 by multiplying it with the integer 3 like so:
Code:
t * 3
.

Here’s an example:

Code:
simple_tuple = ('Alice', 42, 3.14) complex_tuple = simple_tuple * 3 print(complex_tuple) # ('Alice', 42, 3.14, 'Alice', 42, 3.14, 'Alice', 42, 3.14)
Example 3 – Tuple From List

This approach is simple: First, create a list of size n. Second, pass that list into the
Code:
tuple()
function to create a tuple of size
Code:
n
.

Code:
n = 100 # 1. Create list of size n lst = [42] * n # 2. Change value in (mutable) list lst[2] = 'Alice' # 3. Create tuple from list AFTER modification t = tuple(lst) # 4. Print tuple print(t) # (42, 42, 'Alice', 42, 42, ...)

Recommended Tutorial: Create a Listof Size n

Example 4 – Generator Expression (List Comprehension)

You can pass a generator expression into Python’s built-in
Code:
tuple()
function to dynamically create a tuple of elements, given another iterable. For example, the expression
Code:
tuple(i**2 for i in range(10))
creates a tuple with ten square numbers.

Here’s the code snippet for copy&paste:

Code:
x = tuple(i**2 for i in range(10)) print(x) # (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)

In case you need some background on this terrific Python feature, check out my article on List Comprehension and my best-selling Python textbook on writing super condensed and concise Python code:

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

[Image: 3D_cover-1024x944.jpg]

Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:
  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution

  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics

  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning

  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators

  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: