search
HomeBackend DevelopmentPython TutorialCreate a Python program using tuple literals

Create a Python program using tuple literals

Sep 10, 2023 am 11:09 AM
python programtupleLiteral value

Create a Python program using tuple literals

In Python, a tuple is an immutable sequence type typically used to store a collection of items.

Python tuples are very similar to Python lists in terms of nesting, indexing, and repetition, but one difference is that tuples are immutable, while lists are mutable, which means we can change the elements of the list, but not Do the same with tuples. Another difference is that lists are declared using square brackets [] while tuples are declared using simple brackets ().

In this article, we will discuss how to create tuples in Python using tuple literals. We'll introduce the syntax for defining tuples and provide examples of creating tuples using elements of different types.

We can declare a tuple in the following way -

tup1 = ("this" , "is" , “a” , "tuple")
tup2 = (1, 2, 3, 4, 5 )
tup3 = ("a", "b", "c", "d")

There are many ways to create tuples, but in this article, we will see how to create tuples using tuple literals.

Use tuple literals

Before using tuple literals to create tuple literals, let us first understand the meaning of literals in Python. The data we assign to variables and constants when we write code is called literals.

The values ​​of these literals will not change during the entire execution of the program. There are many types of literal in Python, but if we have to refer to a collection type object, such as a list, tuple or dictionary, then we have to use a so-called "Literal Collection".

A tuple literal is an example of a collection of literals that can be used to create a tuple object in Python.

Example

In the following example, we will create a tuple using parentheses and comma declarations.

tuple1 = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 )
print("the tuple is", tuple1 )

Output

The output of the above code is as follows -

the tuple is ( 1 , 2 , 3 , 4 , 5 , 6 , 7 )

Use another list

We will see how to create a tuple using another list. This method is also called type conversion. Essentially, what we do is create an object of type list and convert it to an object of tuple type. Using this method is an unconventional way to create a list, but is mentioned in this article as an alternative in case you need it.

Example

In the example below, we will create a list from another list. The tuple created will have the same elements as the list, but cannot be changed. We can do this by using the tuple() method, which is a built-in method provided by python to convert the data type in it to a tuple.

List1 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
tuple1 = tuple(List1)
print("the tuple is", tuple1 )

Output

The output of the above program is as follows -

the tuple is ( 1 , 2 , 3 , 4 , 5 , 6 , 7 )

Create tuple from string

We will see how to create tuples using form strings . With this approach, all characters of the string will be distinct elements of the created tuple. We can do this by using the tuple() function, which will convert the data type in it to a tuple.

Example

In the example below, we will create a list from strings . With this method, all characters in String will become elements of the tuple in the order in which they appear in String.

string1 = "This is a tuple"
tuple1 = tuple(string1)
print("the tuple is" , tuple1 )

Output

The output of the above program is as follows -

the tuple is ( ‘T’ , ‘h’ , ‘i’ , ‘s’ , ‘ ’ , ‘i’ , ‘s’ , ‘ ’ , ‘a’ , ‘ ’ , ‘t’ , ‘u’ , ‘p’ , ‘l’ , ‘e’ )

in conclusion

In this article, we discussed how tuples are created and their properties. We saw 3 different ways of creating tuples. In the first method, we create a tuple using parentheses with commas separating the elements. In the second method, we create a tuple from the list, in this method all the elements of the tuple are the same as the elements of the list from which it was created. In the third method, we create tuples from strings. All characters of a string are elements of a tuple.

The above is the detailed content of Create a Python program using tuple literals. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor