Python data types

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

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

The following is the standard or built-in Python data type:

numeric

In Python, a numeric data type represents data that has a numeric value. The numeric value can be an integer, floating number, or even a complex number. These values ‚Äã‚Äãare defined in Python as int , float , and complex class.

  • Intergers — this value is represented by the int class. It contains positive or negative integers (no fractional or decimal). There is no limit to the length of the interger in Python.
  • Float — this value is represented by the float class. This is a real floating point number. Indicated by a decimal point. Optionally, the character e or E followed by a positive or negative integer can be added to indicate scientific notation.
  • Complex numbers — A complex number is represented by a complex class. Specified as (real) + (imaginary) j . For example — 2 + 3j

Note. The type () function is used to define the data type.

# Python program for
# show numeric value

a = 5

print ( "Type of a:" , type (a))

b = 5.0

print ( " Type of b: " , type (b))

c = 2 + 4j

print ( "Type of c:" , type (c ))

Output:

 Type of a: & lt; class ’int’ & gt; Type of b: & lt; class ’float’ & gt; Type of c: & lt; class ’complex’ & gt; 

Sequence type

In Python, the sequence — it is an ordered collection of similar or different data types. Sequences allow you to store multiple values ‚Äã‚Äãin an organized and efficient manner. There are several types of sequences in Python:

1) String

In Python, strings — they are arrays of bytes representing Unicode characters. The string — it is a set of one or more characters, enclosed in single, double, or triple quotes. There is no character data type in python, character is a string of length one. It is represented by the str class.

Creating a string

Strings in Python can be created using single or double quotes or even triple quotes.

# Python program for
# Create a line


# Create line
# with single quotes

String1 = ’Welcome to the Geeks World’

print ( " String with the use of Single Quotes: " )

print (String1)


# Create a line
# with double quotes

String1 = "I’ma Geek"

print ( "String with the use of Double Quotes:" )

print (String1)

print ( type (String1))


# Create a line
# with triple quotes

String1 = "I am a geek and I live in a geek world

print ( "String with the use of Triple Quotes:" )

print (String1)

print ( type (String1))


# Create a triple line
# Quotes allow multiple lines

String1 = & # 39; & # 39; & # 39; Geeks

For

Life ""

print ( "Creating a multiline String:" )

print (String1)

Exit :

 String with the use of Single Quotes: Welcome to the Geeks World String with the use of Double Quotes: I ’ma Geek & lt; class’ str’ & gt; String with the use of Triple Quotes: I’ma Geek and I live in a world of "Geeks" & lt; class ’str’ & gt; Creating a multiline String: Geeks For Life 

Accessing string elements

In Python, individual characters in a string can be accessed with using the indexing method. Indexing allows negative address references to access characters at the end of a line, for example, -1 refers to the last character, -2 refers to the second last character, and so on.
Raises IndexError when accessing an index out of range. Only integers are allowed, since index, floating point, or other types will cause TypeError .

# Python program for access
# line characters

String1 = "GeeksForGeeks"

print ( "Initial String:" )

print (String1)


# Print the first o character

print ( "First character of String is: " )

print (String1 [ 0 ])


# Print the last character

print ( " Last character of String is: " )

print (String1 [ - 1 ])

Output:

 Initial String: GeeksForGeeks First character of String is: G Last character of String is: s 

Remove / Update from Strings

In Python, updating or removing characters from a string is not allowed. This will throw an error because assigning an element or removing an element from a string is not supported. This is because strings are immutable, so the elements of a string cannot be changed once assigned. Only newlines can be reassigned to the same name.

# Python program to update / remove
# line character

String1 = "Hello, I’ma Geek"

print ( "Initial String:" )

print (String1)


# Character update
# lines

String1 [ 2 ] = ’p’

print ( "Updating character at 2nd Index: " )

print (String1)


# Deleting a character
# lines

del String1 [ 2 ]

print ( "Deleting character at 2nd Index:" )

print (String1)

Exit :

 Traceback (most recent call last): File "/home/360bb1830c83a918fc78aa8979195653.py‚", line 10, in String1 [2] = ’p ’TypeError:’ str ’object does not s upport item assignment Traceback (most recent call last): File "/home/499e96a61e19944e7e45b7a6e1276742.py‚", line 10, in del String1 [2] TypeError: ’str’ object doesn’t support item deletion 

Escape Sequencing in Python

When printing single and double quoted strings, it raises a SyntaxError because the string already contains single and double quotes and therefore does not can be printed using any of them. Hence, either triple quotes are used to print such a string, or Escape sequences are used to print such strings.
Escape sequences start with a backslash and can be interpreted in different ways. If single quotes are used to represent a string, then all single quotes present in the string must be escaped, and the same is done for double quotes.

# Program Python for
# Escape Sequencing
Line #


# Starting line

String1 = & # 39; & # 39; I’m & # 39; Geek & # 39; & # 39; & # 39; & # 39;

print ( " Initial String with use of Triple Quotes: " )

print (String1)


# Escaping one quote

String1 = ’I’ma" Geek "’

print ( "Escaping Single Quote: " )

print (String1)


# Avoiding double quotes

String1 = "I’ma" Geek ""

print ( " Escaping Double Quotes: " )

print (String1)


# Print paths with
# use escape sequences

String1 = "C: Python Geeks "

print ( "Escaping Backslashes:" )

print (String1)

Exit:

 Initial String with use of Triple Quotes: I’ma " Geek "Escaping Single Quote: I’ma" Geek "Escaping Double Quotes: I’ma" Geek "Escaping Backslashes: C: PythonGeeks 

Note. To to learn more about strings,

# Python program for demonstration
# Create a list


# Create a list

List = []

print ( "Intial blank List:" )

print ( List )


# Create a list with
# use a string

List = [ ’GeeksForGeeks’ ]

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

print ( List )


# Create a list with
# use multiple values ‚Äã‚Äã

List = [ "Geeks" , "For" , "Geeks" ]

print ( "List containi ng multiple values: " )

print ( List [ 0 ])

print ( List [ 2 ])


# Create a multidimensional list
# (Attaching a list to the list)

List = [[ ’Geeks’ , ’ For’ ], [ ’Geeks’ ]]

print ( "Multi-Dimensional List:" )

print ( List )

Exit :

 Intial blank List: [] List with the use of String: [’GeeksForGeeks’] List containing multiple values: Geeks Geeks Multi-Dimensional List : [[’Geeks’,’ For’], [’Geeks’]] 

Adding items to the list

Items can be added to the list using the append () built-in function. Only one element at a time can be added to the list using the append () method. To add an element to the desired position, use the insert () method. Besides the append () and insert () methods, there is another method for adding elements, extend () , this method is used to add multiple elements to the end of the list.

# Python program to demonstrate
# Add items to the list


# Create a list

List = []

print ( "Initial blank List:" )

print ( List )


# Adding elements
# in the list

List . append ( 1 )

List . append ( 2 )

List . append ( 4 )

print ( "List after Addition of Three elements:" )

print ( List )


# Add an element to
# specific position
# (using the insert method)

List . insert ( 3 , 12 )

List . insert ( 0 , ’Geeks’ )

print ( "List after performing Insert Operation:" )

print ( List )


# Adding multiple elements
# to the end of the list
# (using the Extend method)

L ist . extend ([ 8 , ’Geeks’ , ’ Always’ ])

print ( "List after performing Extend Operation: " )

print ( List )

Exit :

 Initial blank List: [] List after Addition of Three elements: [1, 2, 4] List after Insert Operation: [’Geeks’, 1, 2, 4, 12] List after performing Extend Operation: [’ Geeks’, 1, 2, 4, 12, 8, ’Geeks’,’ Always’] 

Accessing items from a list

To access items from a list, refer to the index number. Use the index operator [] to access an item in the list. The index must be an integer. The nested list is accessed using nested indexing. In Python, reverse sequence indices represent positions from the end of an array. Instead of calculating the offset, as in List [len (List) -3] , simply write List [-3] . Negative indexing means start at the end, -1 refers to the last item, -2 refers to the second last item, etc.

# Python program for demonstration
# access an item from the list


# Create a list with
# use multiple values ‚Äã‚Äã

List = [ "Geeks" , "For" , "Geeks" ]


# access to element from
# list by number py index

print ( "Accessing element from the list " )

print ( List [ 0 ])

print ( List [ 2 ])


# access the element using
# negative indexing

print ( "Accessing element using negative indexing " )


# print last list item

print ( List [ - 1 ])


# print the third last item in the list

print ( List [ - 3 ])

Exit:

 Accessing element from the list Geeks Geeks Accessing element using negative indexing Geeks Geeks 

Removing items from the list

Items can be removed from the list with using the built-in remove () function but an error occurs if the element does not exist in the set. The Pop () function can also be used to remove and return an item from a set, but by default it only removes the last item in the set, to remove an item from a specific position in the list, the item index is passed as an argument to the pop () method.

Note: The Remove method in the List will only remove the first occurrence of the item you are looking for.

# Python demo
# Remove items in the list


# Create a list

List = [ 1 , 2 , 3 , 4 , 5 , 6 ,

7 , 8 , 9 , 10 , 11 , 12 ]

print ( "Intial List:" )

print ( List )


# Removing items from the list
# using the Remove () method

List . remove ( 5 )

List .remove ( 6 )

print ( "List after Removal of two elements:" )

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

Python data types __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 data types __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:

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

Want to excel in Python? See our review of the best Python online courses 2023. 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 Galleotti

Boston | 2023-04-01

Thanks for explaining! I was stuck with Python data types for some hours, finally got it done 🤗. Will get back tomorrow with feedback

Carlo OConnell

Moscow | 2023-04-01

I was preparing for my coding interview, thanks for clarifying this - Python data types in Python is not the simplest one. Checked yesterday, it works!

Marie Krasiko

Prague | 2023-04-01

Simply put and clear. Thank you for sharing. Python data types and other issues with re Python module was always my weak point 😁. I am just not quite sure it is the best method

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

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

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers


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

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

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