Python Tuples

| | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Tuples are immutable and typically contain a sequence of dissimilar elements that can be accessed through unboxing or indexing (or even by attribute in the case of named tuples). Lists are mutable, and their elements are usually uniform and accessible by iterating over the list.

Creating a Tuple

In Python, tuples are created by placing a sequence of values, separated by commas, with or without parentheses to group the data sequence. Tuples can contain any number of elements and any data type (e.g. strings, integers, list, etc.). Tuples can also be created with a single element, but this is a bit tricky. Having one element in parentheses is not enough, there must be a comma to make it a tuple.

Note. Creating a Python tuple without using parentheses is called Tuple Packing.

# Python program for demonstration
# Adding items to the Set


# Create an empty tuple

Tuple1 = ()

print ( "Initial empty Tuple:" )

print (Tuple1)


# Create a tuple with
# using strings

Tuple1 = ( ’Geeks’ , ’ For’ )

print ( "Tuple with the use of String:" )

print (Tuple1)


# Create a tuple with
# use a list

list1 = [ 1 , 2 , 4 , 5 , 6 ]

print ( "Tuple using List:" )

print ( tuple (list1 ))


# Create a tuple
# using a loop

Tuple1 = ( ’Geeks’ )

n = 5

print ( "Tuple with a loop" )

for i in range ( int (n)):

Tuple1 = (Tuple1,)

print (Tuple1)


# Create a tuple with
# use inline function

Tuple1 = tuple ( ’Geeks’ )

print ( " Tuple with the use of function: " )

print (Tuple1)


# Create a tuple with
# Mixed data types

Tuple1 = ( 5 , ’Welcome’ , 7 , ’Geeks’ )

print ( "Tuple with Mixed Datatypes:" )

print (Tuple1)


# Create a tuple
# with nested tuples

Tuple1 = ( 0 , 1 , 2 , 3 )

Tuple2 = ( ’ python’ , ’geek’ )

Tuple3 = (Tuple1, Tuple2)

print ( "Tuple with nested tuples:" )

print (Tuple3)


# Create a tuple
# repeat

Tuple1 = ( ’Geeks’ ,) * 3

print ( "Tuple with repetition:" )

print (Tuple1)

Exit:

 Initial empty Tuple: () Tuple with the use of String: (’Geeks’,’ For’) Tuple using List: (1, 2, 4, 5, 6) Tuple with a loop (’Geeks’,) ( (’Geeks’,),) (((’ Geeks’,),),) ((((’Geeks’,),),),) (((((’ Geeks’,),),), ),) Tuple with the use of function: (’G’,’ e’, ’e’,’ k’, ’s’) Tuple with Mixed Datatypes: (5,’ Welcome’, 7, ’Geeks’) Tuple with nested tuples: ((0, 1, 2, 3), (’python’,’ geek’)) Tuple with repetition: (’Geeks’,’ Geeks’, ’Geeks’) 

Tuple Concatenation

Tuple Concatenation — it is the process of combining two or more tuples. Concatenation is done using the "+" operator. Concatenation of tuples is always performed from the end of the original tuple. Other arithmetic operations do not apply to tuples.
Note. In a union, only the same data types can be combined; an error occurs when combining list and tuple.

Exit:

 Tuple 1: (0, 1, 2, 3 ) Tuple2: (’Geeks’,’ For’, ’Geeks’) Tuples after Concatenaton: (0, 1, 2, 3,’ Geeks’, ’For’,’ Geeks’) 

Tuple slicing

Tuple slicing is performed to extract a specific range or slice sub-elements from a tuple. Slicing can also be done for lists and arrays. Indexing into a list will retrieve a single item, while Slicing allows you to retrieve a set of items.
Note. Negative increment values ‚Äã‚Äãcan also be used to change the sequence of tuples.

# Concatenate tuples

Tuple1 = ( 0 , 1 , 2 , 3 )

Tuple2 = ( ’ Geeks’ , ’For’ , ’ Geeks’ )

Tuple3 = Tuple1 + Tuple2


# Print the first tuple

print ( "Tuple 1:" )

print (Tuple1)


# Print the second tuple

print ( " Tuple2: " )

print (Tuple2)


# Print the final tuple

print ( "Tuples after Concatenaton:" )

print (Tuple3)

# Slicing a tuple


# Tuple slicing
# with numbers

Tuple1 = tuple ( ’ GEEKSFORGEEKS’ )


# Remove the first element

print ( "Removal of First Element:" )

print (Tuple1 [ 1 :])


# Reverse tuple

print ( "Tuple after sequence of Element is reversed:" )

print (Tuple1 [:: - 1 ])


# Print range items

print ( "Printing elements between Range 4-9:" )

print (Tup le1 [ 4 : 9 ])

Output:

 Removal of First Element: (’E’,’ E’, ’K’,’ S’, ’F’,’ O’, ’R’,’ G’, ’E’ , ’E’,’ K’, ’S’) Tuple after sequence of Element is reversed: (’ S’, ’K’,’ E’, ’E’,’ G’, ’R’,’ O’, ’F’,’ S’, ’K’,’ E’, ’E’,’ G’) Printing elements between Range 4-9: (’S’,’ F’, ’O’,’ R’, ’ G’) 

Deleting a tuple

Tuples are immutable and therefore do not allow part of it to be deleted. The entire tuple is removed using the del () method.
Note. Printing a tuple after deletion results in an error.

# Removing a tuple

Tuple1 = ( 0 , 1 , 2 , 3 , 4 )

del Tuple1

print (Tuple1)

Traceback (most recent call last):
File "/ home / efa50fd0709dec0 8434191f32275928a.py ‚", line 7, in
print (Tuple1)
NameError: name ’Tuple1’ is not defined

Built-in Methods

Built-in Function Description
all () Returns true if all element are true or if tuple is empty
any () return true if any element of the tuple is true. if tuple is empty, return false
len () Returns length of the tuple or size of the tuple
enumerate () Returns enumerate object of tuple
max () return maximum element of given tuple
min() return minimum element of given tuple
sum () Sums up the numbers in the tuple
sorted () input elements in the tuple and return a new sorted list
tuple () Convert an iterable to a tuple.

< h3> Latest articles on Tuple

Program Tuples

👻 Read also: what is the best laptop for engineering students?

Python Tuples __del__: Questions

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.

2973

Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

2973

Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

Python Tuples __del__: Questions

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

2639

Answer #2


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

2639

Answer #3

Python syntax to delete a file

import os
os.remove("/tmp/<file_name>.txt")

Or

import os
os.unlink("/tmp/<file_name>.txt")

Or

pathlib Library for Python version >= 3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

Unlink method used to remove the file or the symbolik link.

If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.

Best practice

  1. First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
    a. os.path.isfile("/path/to/file")
    b. Use exception handling.

EXAMPLE for os.path.isfile

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

## If file exists, delete it ##
if os.path.isfile(myfile):
    os.remove(myfile)
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

Exception Handling

#!/usr/bin/python
import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
try:
    os.remove(myfile)
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))

RESPECTIVE OUTPUT

Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.

Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.

Enter file name to delete : foo.txt

Python syntax to delete a folder

shutil.rmtree()

Example for shutil.rmtree()

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

Is there a simple way to delete a list element by value?

5 answers

I want to remove a value from a list if it exists in the list (which it may not).

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)

The above case (in which it does not exist) shows the following error:

Traceback (most recent call last):
  File "D:zjm_codea.py", line 6, in <module>
    b = a.index(6)
ValueError: list.index(x): x not in list

So I have to do this:

a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print(a)

But is there not a simpler way to do this?

1055

Answer #1

To remove an element"s first occurrence in a list, simply use list.remove:

>>> a = ["a", "b", "c", "d"]
>>> a.remove("b")
>>> print(a)
["a", "c", "d"]

Mind that it does not remove all occurrences of your element. Use a list comprehension for that.

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]

We hope this article has helped you to resolve the problem. Apart from Python Tuples, check other __del__-related topics.

Want to excel in Python? See our review of the best Python online courses 2022. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Anna Sikorski

Berlin | 2022-12-10

Maybe there are another answers? What Python Tuples exactly means?. Will use it in my bachelor thesis

Jan Lehnman

Abu Dhabi | 2022-12-10

Thanks for explaining! I was stuck with Python Tuples for some hours, finally got it done 🤗. Will use it in my bachelor thesis

Carlo Sikorski

Boston | 2022-12-10

sin is always a bit confusing 😭 Python Tuples is not the only problem I encountered. Checked yesterday, it works!

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically