Create an account


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 * with a tuple with one element (42,) as a right operand and the number of repetitions of this element as a left operand. For example, the expression (42,) * n creates the tuple (42, 42, 42, 42, 42) for n=5.

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

Exercise: Initialize the tuple with n=20 placeholder elements -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 n. How to initialize a tuple with n placeholder elements (e.g., 42)?

# n=0 --> ()
# n=1 --> (42,)
# n=5 --> (42, 42, 42, 42, 42)

Example 1 – Tuple Concatenation


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

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 TypeError: 'tuple' object does not support item assignment.

>>> 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 n. For example, given a tuple t of size 3, you can create a tuple of size 9 by multiplying it with the integer 3 like so: t * 3.

Here’s an example:

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 tuple() function to create a tuple of size n.

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 List of Size n

Example 4 – Generator Expression (List Comprehension)


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

Here’s the code snippet for copy&paste:

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.

Python One-Liners

Python One-Liners will 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!!



https://www.sickgaming.net/blog/2022/08/...of-size-n/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python IndexError: Tuple Index Out of Range [Easy Fix] xSicKxBot 0 1,950 08-22-2023, 09:07 AM
Last Post: xSicKxBot
  [Tut] Python Tuple Concatenation: A Simple Illustrated Guide xSicKxBot 0 1,943 08-21-2023, 10:25 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,697 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] I Used These 3 Easy Steps to Create a Bitcoin Wallet in Python (Public/Private) xSicKxBot 0 1,227 01-29-2023, 02:51 AM
Last Post: xSicKxBot
  [Tut] How to Create and Run a Batch File That Runs a Python Script? xSicKxBot 0 1,242 11-09-2022, 09:53 PM
Last Post: xSicKxBot
  [Tut] Python Create JSON File xSicKxBot 0 1,258 11-03-2022, 01:09 PM
Last Post: xSicKxBot
  [Tut] Python Set to Tuple | Tuple to Set | 3 Easy Ways xSicKxBot 0 1,199 09-21-2022, 10:33 PM
Last Post: xSicKxBot
  [Tut] How to Create an Empty List in Python? xSicKxBot 0 1,114 07-07-2022, 02:50 PM
Last Post: xSicKxBot
  [Tut] Python Tuple Comprehension Doesn’t Exist – Use This Instead xSicKxBot 0 1,150 06-04-2022, 12:46 PM
Last Post: xSicKxBot
  [Tut] How to Convert List of Lists to Tuple of Tuples in Python? xSicKxBot 0 1,253 06-02-2022, 08:39 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016