logo

Python Numerical Methods

../_images/book_cover.jpg

This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists , the content is also available at Berkeley Python Numerical Methods .

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license . If you find this content useful, please consider supporting the work on Elsevier or Amazon !

< 2.0 Variables and Basic Data Structures | Contents | 2.2 Data Structure - Strings >

Variables and Assignment ¶

When programming, it is useful to be able to store information in variables. A variable is a string of characters and numbers associated with a piece of information. The assignment operator , denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable. Until the value is changed or the variable deleted, the character x behaves like the value 1.

TRY IT! Assign the value 2 to the variable y. Multiply y by 3 to show that it behaves like the value 2.

A variable is more like a container to store the data in the computer’s memory, the name of the variable tells the computer where to find this value in the memory. For now, it is sufficient to know that the notebook has its own memory space to store all the variables in the notebook. As a result of the previous example, you will see the variable “x” and “y” in the memory. You can view a list of all the variables in the notebook using the magic command %whos .

TRY IT! List all the variables in this notebook

Note that the equal sign in programming is not the same as a truth statement in mathematics. In math, the statement x = 2 declares the universal truth within the given framework, x is 2 . In programming, the statement x=2 means a known value is being associated with a variable name, store 2 in x. Although it is perfectly valid to say 1 = x in mathematics, assignments in Python always go left : meaning the value to the right of the equal sign is assigned to the variable on the left of the equal sign. Therefore, 1=x will generate an error in Python. The assignment operator is always last in the order of operations relative to mathematical, logical, and comparison operators.

TRY IT! The mathematical statement x=x+1 has no solution for any value of x . In programming, if we initialize the value of x to be 1, then the statement makes perfect sense. It means, “Add x and 1, which is 2, then assign that value to the variable x”. Note that this operation overwrites the previous value stored in x .

There are some restrictions on the names variables can take. Variables can only contain alphanumeric characters (letters and numbers) as well as underscores. However, the first character of a variable name must be a letter or underscores. Spaces within a variable name are not permitted, and the variable names are case-sensitive (e.g., x and X will be considered different variables).

TIP! Unlike in pure mathematics, variables in programming almost always represent something tangible. It may be the distance between two points in space or the number of rabbits in a population. Therefore, as your code becomes increasingly complicated, it is very important that your variables carry a name that can easily be associated with what they represent. For example, the distance between two points in space is better represented by the variable dist than x , and the number of rabbits in a population is better represented by nRabbits than y .

Note that when a variable is assigned, it has no memory of how it was assigned. That is, if the value of a variable, y , is constructed from other variables, like x , reassigning the value of x will not change the value of y .

EXAMPLE: What value will y have after the following lines of code are executed?

WARNING! You can overwrite variables or functions that have been stored in Python. For example, the command help = 2 will store the value 2 in the variable with name help . After this assignment help will behave like the value 2 instead of the function help . Therefore, you should always be careful not to give your variables the same name as built-in functions or values.

TIP! Now that you know how to assign variables, it is important that you learn to never leave unassigned commands. An unassigned command is an operation that has a result, but that result is not assigned to a variable. For example, you should never use 2+2 . You should instead assign it to some variable x=2+2 . This allows you to “hold on” to the results of previous commands and will make your interaction with Python must less confusing.

You can clear a variable from the notebook using the del function. Typing del x will clear the variable x from the workspace. If you want to remove all the variables in the notebook, you can use the magic command %reset .

In mathematics, variables are usually associated with unknown numbers; in programming, variables are associated with a value of a certain type. There are many data types that can be assigned to variables. A data type is a classification of the type of information that is being stored in a variable. The basic data types that you will utilize throughout this book are boolean, int, float, string, list, tuple, dictionary, set. A formal description of these data types is given in the following sections.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List

Python Tuple

  • Python String

Python Sets

Python Dictionary

  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python Numbers, Type Conversion and Mathematics

  • Python Dictionary items()
  • Python List extend()
  • Python Data Types

In computer programming, data types specify the type of data that can be stored inside a variable. For example,

Here, 24 (an integer) is assigned to the num variable. So the data type of num is of the int class.

Data Types Classes Description
Numeric int, float, complex holds numeric values
String str holds sequence of characters
Sequence list, tuple, range holds collection of items
Mapping dict holds data in key-value pair form
Boolean bool holds either or
Set set, frozenset hold collection of unique items

Since everything is an object in Python programming, data types are actually classes and variables are instances(object) of these classes.

  • Python Numeric Data type

In Python, numeric data type is used to hold numeric values.

Integers, floating-point numbers and complex numbers fall under Python numbers category. They are defined as int , float and complex classes in Python.

  • int - holds signed integers of non-limited length.
  • float - holds floating decimal points and it's accurate up to 15 decimal places.
  • complex - holds complex numbers.

We can use the type() function to know which class a variable or a value belongs to.

Let's see an example,

In the above example, we have created three variables named num1 , num2 and num3 with values 5 , 5.0 , and 1+2j respectively.

We have also used the type() function to know which class a certain variable belongs to.

  • 5 is an integer value, type() returns int as the class of num1 i.e <class 'int'>
  • 2.0 is a floating value, type() returns float as the class of num2 i.e <class 'float'>
  • 1 + 2j is a complex number, type() returns complex as the class of num3 i.e <class 'complex'>
  • Python List Data Type

List is an ordered collection of similar or different types of items separated by commas and enclosed within brackets [ ] . For example,

Here, we have created a list named languages with 3 string values inside it.

Access List Items

To access items from a list, we use the index number (0, 1, 2 ...) . For example,

In the above example, we have used the index values to access items from the languages list.

  • languages[0] - access first item from languages i.e. Swift
  • languages[2] - access third item from languages i.e. Python

To learn more about lists, visit Python List .

  • Python Tuple Data Type

Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.

In Python, we use the parentheses () to store items of a tuple. For example,

Here, product is a tuple with a string value Xbox and integer value 499.99 .

Access Tuple Items

Similar to lists, we use the index number to access tuple items in Python . For example,

To learn more about tuples, visit Python Tuples .

  • Python String Data Type

String is a sequence of characters represented by either single or double quotes. For example,

In the above example, we have created string-type variables: name and message with values 'Python' and 'Python for beginners' respectively.

To learn more about strings, visit Python Strings .

  • Python Set Data Type

Set is an unordered collection of unique items. Set is defined by values separated by commas inside braces { } . For example,

Here, we have created a set named student_info with 5 integer values.

Since sets are unordered collections, indexing has no meaning. Hence, the slicing operator [] does not work.

To learn more about sets, visit Python Sets .

  • Python Dictionary Data Type

Python dictionary is an ordered collection of items. It stores elements in key/value pairs.

Here, keys are unique identifiers that are associated with each value.

In the above example, we have created a dictionary named capital_city . Here,

  • Keys are 'Nepal' , 'Italy' , 'England'
  • Values are 'Kathmandu' , 'Rome' , 'London'

Access Dictionary Values Using Keys

We use keys to retrieve the respective value . But not the other way around. For example,

Here, we have accessed values using keys from the capital_city dictionary.

Since 'Nepal' is key, capital_city['Nepal'] accesses its respective value i.e. Kathmandu

However, 'Kathmandu' is the value for the 'Nepal' key, so capital_city['Kathmandu'] throws an error message.

To learn more about dictionaries, visit Python Dictionary .

Table of Contents

  • Introduction

Sorry about that.

Related Tutorials

Python Tutorial

logo

Introduction to Data Science I & II

Data types #.

Evelyn Campbell, Ph.D.

Python offers a number of different data types that can be manipulated and used by various functions. Some important built-in Python data types include booleans , strings , integers , and floats . These data types can be used to build various data structures, such as lists, dictionaries, arrays, and dataframes, which will be covered in Chapters 4 and 6 . Here we will explore each data type and corresponding functions that are useful when working with these data types.

Booleans are a data type that consist of two possible outcomes: True or False . Under the hood, these values take on a binary value, where True is equal to 1 and False is equal to 0. Booleans are very commonly used with comparison operators (discussed more in Section 3.4 ), and because they also can have a numeric meaning, they can be used in calculations as well. Let’s start with a simple example of a Boolean.

Above, the variable boolval is equated to the expression 5 < 3 , which reads “5 is less than 3.” Because 5 is not in fact less than 3, the entire statement is False , and this Boolean value is assigned to boolval .

Below, we add 5 to the value of boolval . Recall that False has a numerical value of 0, so essentially, boolval + 5 is the same as 0 + 5:

Using the variable directly in a comparison expression, we can see that the value of boolval is less than 10, and thus returns another Boolean value of True :

Python has built-in functions that use values and variables as input to perform a task and produce an output. We have already used some basic functions, such as the print() function, and we will learn about a few more that are associated with datatypes. Built-in functions will be further discussed in section Section 3.5 .

For now, we will use a few basic functions associated with data types. The bool() function converts an input (i.e. a numeric value, string, or even data structures) to a boolean value.

Any input that has value will give an output of True when called into the bool() function. Any input that is null or empty will give a False output.

A string a data type that can consist of concatenated alphanumeric and punctuation characters. According to the Merriam-Webster dictionary, to concatenate means to link together in a series or chain .

Strings are recognized by Python through the use of single (’ ‘), double (” “), or triple (‘’’ ‘’’) quotation marks.

Double quotes are recommended as a first option use, as they allow for the use of single quotations inside.

The above error can be fixed by an escape sequence . Escape sequences are string modifiers that allow for the use of certain characters that would otherwise be misinterpreted by Python. Because strings are created by the use of quotes, the escape sequences \' and \" allow for the use of quotes as part of a string:

Other useful escape sequences include \n and \t . These allow for a new line and tab spacing to be added to a string, respectively.

Strings can be used in simple additive mathematical operations, like addition and multiplication, resulting in concatenation of the strings:

In the above example, we see that Python prints the sentence twice, but these sentences run into each other (i.e. there is no space in between). We have to specifically tell Python to add this space. We can do this by printing the string variables that we want along with a space in quotation marks (” “). We can also do this by adding multiple arguments to the print() function, separated by a comma.

Escape sequences also can be used in the print() function as an argument or through concatenation:

When manipulating string variables, data scientists will often use what are called methods . A method is piece of code that is associated with a defined variable, as opposed to a function which uses defined variables as input arguments for parameters. Functions will be further discussed in the upcoming section.

Some methods can be used on strings to quickly and efficiently alter them. A few include the .upper() , .lower() , .capitalize() , .title() , and .swapcase() methods. There are many others, but these few are great to start exploring the different ways string variables can be manipulated:

A really useful method that can be used on strings is the .replace() method. This method allows you to replace a given string expression with a new one of your choosing:

Numeric values can also be recognized as a string by putting them within quotation marks or using them as an argument in the str() function.

We can confirm that these are indeed strings by calling the type() function on these variables, which can be used on any variable to check its data type.

Keep in mind that when a numerical value is converted to a string, it can no longer be used to perform certain mathematical calculations, such as division, subtraction, or exponentiation.

It can be used in addition and multiplication, but more so in a “stringy” way and not a “mathy” way:

This is the only time when 2 + 2 equals 22. 🙃

Integers & Floats #

Integers and floats are numerical data types that are often used to perform mathematical operations. Integers consist of whole numbers, while floats consist of whole numbers with floating decimal places. Floats can hold up to 15 significant figures following the decimal point and can be used to obtain more accurate calculations. However, it is easier and faster for a computer to do calculations using integers. Thus, one must weigh the pros and cons of using these data types when doing calculations and writing functions to obtain outcomes that are most aligned with their end goals. Let’s take a look at these data types in use.

These numerical data types can be converted between floats and integers using the float() and int() functions. Let’s see what happens when we convert the integer value 4567 to a float and the float value 45.67 to an integer:

We can see that the conversion of an integer to a float simply adds one significant figure after the decimal place. Moreover, converting a float to an integer rounds the number down to the nearest whole number. We can also convert numerical values in strings and boolean data types to integers and floats

Remember, the int() and float() functions can only convert recognized numerical values. A string of letters cannot be converted to a float or integer.

By understanding data types, we can begin to use them in other analyses and functionalities in Python. Next, we will learn how to use data types in comparisons, which can help further down the line in functions ( Chapter 3.5 ), for loops ( Chapter 5.3 ), and subsetting data from DataFrames ( Chapter 6.6 ).

previous episode

Python for absolute beginners, next episode, variables and assignment.

Overview Teaching: 15 min Exercises: 15 min Questions How can I store data in programs? Objectives Write scripts that assign values to variables and perform calculations with those values. Correctly trace value changes in scripts that use assignment.

Use variables to store values

Variables are one of the fundamental building blocks of Python. A variable is like a tiny container where you store values and data, such as filenames, words, numbers, collections of words and numbers, and more.

The variable name will point to a value that you “assign” it. You might think about variable assignment like putting a value “into” the variable, as if the variable is a little box 🎁

(In fact, a variable is not a container as such but more like an adress label that points to a container with a given value. This difference will become relevant once we start talking about lists and mutable data types.)

You assign variables with an equals sign ( = ). In Python, a single equals sign = is the “assignment operator.” (A double equals sign == is the “real” equals sign.)

  • Variables are names for values.
  • In Python the = symbol assigns the value on the right to the name on the left.
  • The variable is created when a value is assigned to it.
  • Here, Python assigns an age to a variable age and a name in quotation marks to a variable first_name :

Variable names

Variable names can be as long or as short as you want, but there are certain rules you must follow.

  • Cannot start with a digit.
  • Cannot contain spaces, quotation marks, or other punctuation.
  • May contain an underscore (typically used to separate words in long variable names).
  • Having an underscore at the beginning of a variable name like _alistairs_real_age has a special meaning. So we won’t do that until we understand the convention.
  • The standard naming convention for variable names in Python is the so-called “snake case”, where each word is separated by an underscore. For example my_first_variable . You can read more about naming conventions in Python here .

Use meaningful variable names

Python doesn’t care what you call variables as long as they obey the rules (alphanumeric characters and the underscore). As you start to code, you will almost certainly be tempted to use extremely short variables names like f . Your fingers will get tired. Your coffee will wear off. You will see other people using variables like f . You’ll promise yourself that you’ll definitely remember what f means. But you probably won’t.

So, resist the temptation of bad variable names! Clear and precisely-named variables will:

  • Make your code more readable (both to yourself and others).
  • Reinforce your understanding of Python and what’s happening in the code.
  • Clarify and strengthen your thinking.

Use meaningful variable names to help other people understand what the program does. The most important “other person” is your future self!

Python is case-sensitive

Python thinks that upper- and lower-case letters are different, so Name and name are different variables. There are conventions for using upper-case letters at the start of variable names so we will use lower-case letters for now.

Off-Limits Names

The only variable names that are off-limits are names that are reserved by, or built into, the Python programming language itself — such as print , True , and list . Some of these you can overwrite into variable names (not ideal!), but Jupyter Lab (and many other environments and editors) will catch this by colour coding your variable. If your would-be variable is colour-coded green, rethink your name choice. This is not something to worry too much about. You can get the object back by resetting your kernel.

Use print() to display values

We can check to see what’s “inside” variables by running a cell with the variable’s name. This is one of the handiest features of a Jupyter notebook. Outside the Jupyter environment, you would need to use the print() function to display the variable.

You can run the print() function inside the Jupyter environment, too. This is sometimes useful because Jupyter will only display the last variable in a cell, while print() can display multiple variables. Additionally, Jupyter will display text with \n characters (which means “new line”), while print() will display the text appropriately formatted with new lines.

  • Python has a built-in function called print() that prints things as text.
  • Provide values to the function (i.e., the things to print) in parentheses.
  • To add a string to the printout, wrap the string in single or double quotations.
  • The values passed to the function are called ‘arguments’ and are separated by commas.
  • When using the print() function, we can also separate with a ‘+’ sign. However, when using ‘+’ we have to add spaces in between manually.
  • print() automatically puts a single space between items to separate them.
  • And wraps around to a new line at the end.

Variables must be created before they are used

If a variable doesn’t exist yet, or if the name has been misspelled, Python reports an error (unlike some languages, which “guess” a default value).

The last line of an error message is usually the most informative. This message lets us know that there is no variable called eye_color in the script.

Variables Persist Between Cells Variables defined in one cell exist in all other cells once executed, so the relative location of cells in the notebook do not matter (i.e., cells lower down can still affect those above). Notice the number in the square brackets [ ] to the left of the cell. These numbers indicate the order, in which the cells have been executed. Cells with lower numbers will affect cells with higher numbers as Python runs the cells chronologically. As a best practice, we recommend you keep your notebook in chronological order so that it is easier for the human eye to read and make sense of, as well as to avoid any errors if you close and reopen your project, and then rerun what you have done. Remember: Notebook cells are just a way to organize a program! As far as Python is concerned, all of the source code is one long set of instructions.

Variables can be used in calculations

  • We can use variables in calculations just as if they were values. Remember, we assigned 42 to age a few lines ago.

This code works in the following way. We are reassigning the value of the variable age by taking its previous value (42) and adding 3, thus getting our new value of 45.

Use an index to get a single character from a string

  • The characters (individual letters, numbers, and so on) in a string are ordered. For example, the string ‘AB’ is not the same as ‘BA’. Because of this ordering, we can treat the string as a list of characters.
  • Each position in the string (first, second, etc.) is given a number. This number is called an index or sometimes a subscript.
  • Indices are numbered from 0 rather than 1.
  • Use the position’s index in square brackets to get the character at that position.

Use a slice to get a substring

A part of a string is called a substring. A substring can be as short as a single character. A slice is a part of a string (or, more generally, any list-like thing). We take a slice by using [start:stop] , where start is replaced with the index of the first element we want and stop is replaced with the index of the element just after the last element we want. Mathematically, you might say that a slice selects [start:stop] . The difference between stop and start is the slice’s length. Taking a slice does not change the contents of the original string. Instead, the slice is a copy of part of the original string.

Use the built-in function len() to find the length of a string

The built-in function len() is used to find the length of a string (and later, of other data types, too).

Note that the result is 6 and not 7. This is because it is the length of the value of the variable (i.e. 'helium' ) that is being counted and not the name of the variable (i.e. element )

Also note that nested functions are evaluated from the inside out, just like in mathematics. Thus, Python first reads the len() function, then the print() function.

Choosing a Name Which is a better variable name, m , min , or minutes ? Why? Hint: think about which code you would rather inherit from someone who is leaving the library: ts = m * 60 + s tot_sec = min * 60 + sec total_seconds = minutes * 60 + seconds Solution minutes is better because min might mean something like “minimum” (and actually does in Python, but we haven’t seen that yet).
Swapping Values Draw a table showing the values of the variables in this program after each statement is executed. In simple terms, what do the last three lines of this program do? x = 1.0 y = 3.0 swap = x x = y y = swap Solution swap = x # x->1.0 y->3.0 swap->1.0 x = y # x->3.0 y->3.0 swap->1.0 y = swap # x->3.0 y->1.0 swap->1.0 These three lines exchange the values in x and y using the swap variable for temporary storage. This is a fairly common programming idiom.
Predicting Values What is the final value of position in the program below? (Try to predict the value without running the program, then check your prediction.) initial = "left" position = initial initial = "right" Solution initial = "left" # Initial is assigned the string "left" position = initial # Position is assigned the variable initial, currently "left" initial = "right" # Initial is assigned the string "right" print(position) left The last assignment to position was “left”
Can you slice integers? If you assign a = 123 , what happens if you try to get the second digit of a ? Solution Numbers are not stored in the written representation, so they can’t be treated like strings. a = 123 print(a[1]) TypeError: 'int' object is not subscriptable
Slicing What does the following program print? library_name = 'social sciences' print('library_name[1:3] is:', library_name[1:3]) If thing is a variable name, low is a low number, and high is a high number: What does thing[low:high] do? What does thing[low:] (without a value after the colon) do? What does thing[:high] (without a value before the colon) do? What does thing[:] (just a colon) do? What does thing[number:negative-number] do? Solution library_name[1:3] is: oc It will slice the string, starting at the low index and ending an element before the high index It will slice the string, starting at the low index and stopping at the end of the string It will slice the string, starting at the beginning on the string, and ending an element before the high index It will print the entire string It will slice the string, starting the number index, and ending a distance of the absolute value of negative-number elements from the end of the string
Key Points Use variables to store values. Use meaningful variable names. Python is case-sensitive. Use print() to display values. Variables must be created before they are used. Variables persist between cells. Variables can be used in calculations. Use an index to get a single character from a string. Use a slice to get a substring. Use the built-in function len to find the length of a string.

Python Programming

Python Data Types

Updated on:  September 26, 2022 | 11 Comments

Data types specify the different sizes and values that can be stored in the variable . For example, Python stores numbers, strings, and a list of values using different data types.

Table of contents

Example list creation and manipulation, example tuple creation and manipulation, example dictionary creation and manipulation, example set creation and manipulation, bool data type, range data type.

Python is a dynamically typed language; therefore, we do not need to specify the variable’s type while declaring it. Whatever value we assign to the variable based on that data type will be automatically assigned. For example, name = 'Jessa' here Python will store the name variable as a str data type.

No matter what value is stored in a variable (object), a variable can be any type like int, float, str, list, set, tuple, dict, bool, etc.

Also, Solve :

  • Python variables and data type Quiz
  • Basic Python exercise for beginners

There are mainly four types of basic/primitive data types available in Python

  • Numeric : int, float, and complex
  • Sequence : String, list, and tuple
  • Dictionary (dict)

Python data types

To check the data type of variable use the built-in function type()   and isinstance() .

  • The type() function returns the data type of the variable
  • The isinstance() function checks whether an object belongs to a particular class.

In this article, we will learn the following Python data types in detail.

Data typeDescriptionExample
To store integer values
To store decimal values
To store complex numbers (real and imaginary part)
strTo store textual/string data
boolTo store boolean values
listTo store a sequence of mutable data
tupleTo store sequence immutable data
dictTo store key: value pair
setTo store unorder and unindexed values
frozensetTo store immutable version of the set
rangeTo generate a sequence of number
bytesTo store bytes values

Str data type

In Python, A string is a sequence of characters enclosed within a single quote or double quote . These characters could be anything like letters, numbers, or special symbols enclosed within double quotation marks. For example, "PYnative" is a string.

The string type in Python is represented using a  str class.

To work with text or character data in Python, we use Strings. Once a string is created, we can do many operations on it, such as searching inside it, creating a substring from it, and splitting it.

Note : The string is immutable, i.e., it can not be changed once defined. You need to create a copy of it if you want to modify it. This non-changeable behavior is called immutability.

Int data type

Python uses the int data type to represent whole integer values . For example, we can use the int data type to store the roll number of a student. The Integer type in Python is represented using a int class.

You can store positive and negative integer numbers of any length such as 235, -758, 235689741.

We can create an integer variable using the two ways

  • Directly assigning an integer value to a variable
  • Using a int() class.

You can also store integer values other than base 10 such as

  • Binary (base 2)
  • Octal (base 8)
  • Hexadecimal numbers (base 16)

Float data type

To represent floating-point values or decimal value s, we can use the float data type. For example, if we want to store the salary, we can use the float type.

The float type in Python is represented using a float class.

We can create a float variable using the two ways

  • Directly assigning a float value to a variable
  • Using a float() class.

Floating-point values can be represented using the exponential form, also called  scientific notation. The benefit of using the exponential form to represent floating-point values is we can represent large values using less memory.

Complex data type

A complex number is a number with a real and an imaginary component represented as a+bj where a and b contain integers or floating-point values.

The complex type is generally used in scientific applications and electrical engineering applications. If we want to declare a complex value, then we can use the a+bj form. See the following example.

The real part of the complex number is represented using an integer value. The integer value can be in the form of either decimal, float, binary, or hexadecimal. But  the imaginary part  should be represented using  the decimal form only. If we are trying to represent an imaginary part as binary, hex, or octal, we will get an error.

List data type

The Python List is an ordered collection (also known as a sequence ) of elements . List elements can be accessed, iterated, and removed according to the order they inserted at the creation time.

We use the list data type to represent groups of the element as a single entity.  For example: If we want to store all student’s names, we can use list type.

  • The list can contain data of all data types such as  int , float , string
  • Duplicates elements are allowed in the list
  • The list is mutable which means we can modify the value of list elements

We can create a list using the two ways

  • By enclosing elements in the square brackets [] .
  • Using a list() class.

Tuple data type

Tuples are ordered collections of elements that are unchangeab le. The tuple is the same as the list , except the tuple is immutable means we can’t modify the tuple once created.

In other words, we can say a tuple is a read-only version of the list.

For example: If you want to store the roll numbers of students that you don’t change, you can use the tuple data type.

Note : Tuple maintains the insertion order and also, allows us to store duplicate elements.

We can create a tuple using the two ways

  • By enclosing elements in the parenthesis ()
  • Using a tuple() class.

Tuple is immutable

A tuple is immutable means once we create a tuple, we can’t modify it

Dict data type

In Python, dictionaries are unordered collections of unique values stored in (Key-Value) pairs . Use a dictionary data type to store data as a key-value pair.

The dictionary type is represented using a dict class. For example, If you want to store the name and roll number of all students, then you can use the dict type.

In a dictionary, duplicate keys are not allowed, but the value can be duplicated. If we try to insert a value with a duplicate key, the old value will be replaced with the new value.

Dictionary has some characteristics which are listed below:

  • A heterogeneous (i.e., str , list , tuple ) elements are allowed for both key and value in a dictionary. But An object can be a key in a dictionary if it is hashable.
  • The dictionary is mutable which means we can modify its items
  • Dictionary is unordered so we can’t perform indexing and slicing

We can create a dictionary using the two ways

  • By enclosing key and values in the curly brackets {}
  • Using a dict() class.

Set data type

In Python, a set is an unordered collection of data items that are unique . In other words, Python Set is a collection of elements (Or objects) that contains no duplicate elements.

In Python, the Set data type used to represent a group of unique elements as a single entity. For example, If we want to store student ID numbers, we can use the set data type.

The Set data type in Python is represented using a set  class.

We can create a Set using the two ways

  • By enclosing values in the curly brackets {}
  • Using a set() class.

The set data type has the following characteristics.

  • It is mutable which means we can change set items
  • Duplicate elements are not allowed
  • Heterogeneous (values of all data types) elements are allowed
  • Insertion order of elements is not preserved, so we can’t perform indexing on a Set

The  frozenset data type is used to create the immutable Set .  Once we create a  frozenset , then we can’t perform any changes on it.

Use a frozenset()  class to create a  frozenset .

Note : If we try to perform operations like add, remove on  frozenset , you will get an error.

In Python, to represent boolean values ( True and False ) we use the bool data type. Boolean values are used to evaluate the value of the expression. For example, when we compare two values, the expression is evaluated, and Python returns the boolean True or False .

Bytes data type

The bytes data type represents a group of byte numbers just like an array. We use the bytes() constructor to create bytes type, which also returns a bytes object. Bytes are immutable (Cannot be changed).

Use bytes data type if we want to handle binary data like images, videos, and audio files.

In bytes, allowed values are 0 to 256 . If we are trying to use any other values, then we will get a ValueError .

The bytearray data type same as the bytes type except bytearray mutable (we can modify its elements). The bytearray() constructor returns a bytearray object.

In Python, The built-in function  range() used to generate a sequence of numbers from a start number up to the stop number. For example, If we want to represent the roll number from 1 to 20, we can use the range() type. By default, it returns an iterator object that we can iterate using a for loop .

The memoryview is used to create a view of the internal data of an object without copying it. So with the help of memoryview we can see the same data in a different view.

To do this, we need a buffer protocol. The buffer protocol provides a way to access the internal data of an object. This internal data is a memory array or a buffer.

In Python bytes and bytearray are built-in objects that support the buffer protocol. So we can create memoryview on top of those objects.

Syntax to create a memoryview  

Example 1: Creating memoryview of an object

In the above example, we create memoryview of b_array and print the object in memory view format instead of the original object. If we want an object in its original form, we need to collect the object in a container(like a list or tuple). We can also iterate over each element of the given bytes array.

Example 2: Creating and storing in a container

We can also perform indexing and slicing on memoryview same like list and tuple object. So it will return ordinal value for characters at the given index

Example 3: Indexing and slicing on memoryview

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

assignment data type

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Loading comments... Please wait.

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

Basic Data Types in Python

Basic Data Types in Python: A Quick Exploration

Table of Contents

Python’s Basic Data Types

Integer literals, integer methods, the built-in int() function, floating-point literals, floating-point numbers representation, floating-point methods, the built-in float() function, complex number literals, complex number methods, the built-in complex() function, regular string literals, escape sequences in strings, raw string literals, f-string literals, string methods, common sequence operations on strings, the built-in str() and repr() functions, bytes literals, the built-in bytes() function, the built-in bytearray() function, bytes and bytearray methods, boolean literals, the built-in bool() function.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Basic Data Types in Python

Python has several basic data types that are built into the language. With these types, you can represent numeric values, text and binary data, and Boolean values in your code. So, these data types are the basic building blocks of most Python programs and projects.

In this tutorial, you’ll learn about:

  • Numeric types, such as int , float , and complex
  • The str data type, which represents textual data
  • The bytes and bytearray data types for storing bytes
  • Boolean values with the bool data type

In this tutorial, you’ll learn only the basics of each data type. To learn more about a specific data type, you’ll find useful resources in the corresponding section.

Get Your Code: Click here to download the free sample code that you’ll use to learn about basic data types in Python.

Take the Quiz: Test your knowledge with our interactive “Basic Data Types in Python: A Quick Exploration” quiz. You’ll receive a score upon completion to help you track your learning progress:

Interactive Quiz

Take this quiz to test your understanding of the basic data types that are built into Python, like numbers, strings, bytes, and Booleans.

Python has several built-in data types that you can use out of the box because they’re built into the language. From all the built-in types available, you’ll find that a few of them represent basic objects, such as numbers, strings and characters, bytes, and Boolean values.

Note that the term basic refers to objects that can represent data you typically find in real life, such as numbers and text. It doesn’t include composite data types, such as lists , tuples , dictionaries , and others.

In Python, the built-in data types that you can consider basic are the following:

Class Basic Type
Integer numbers
Floating-point numbers
Complex numbers
Strings and characters
, Bytes
Boolean values

In the following sections, you’ll learn the basics of how to create, use, and work with all of these built-in data types in Python.

Integer Numbers

Integer numbers are whole numbers with no decimal places. They can be positive or negative numbers. For example, 0 , 1 , 2 , 3 , -1 , -2 , and -3 are all integers. Usually, you’ll use positive integer numbers to count things.

In Python, the integer data type is represented by the int class:

In the following sections, you’ll learn the basics of how to create and work with integer numbers in Python.

When you need to use integer numbers in your code, you’ll often use integer literals directly. Literals are constant values of built-in types spelled out literally, such as integers. Python provides a few different ways to create integer literals. The most common way is to use base-ten literals that look the same as integers look in math:

Here, you have three integer numbers: a positive one, a negative one, and zero. Note that to create negative integers, you need to prepend the minus sign ( - ) to the number.

Python has no limit to how long an integer value can be. The only constraint is the amount of memory your system has. Beyond that, an integer can be as long as you need:

For a really, really long integer, you can get a ValueError when converting it to a string:

If you need to print an integer number beyond the 4300-digit limit, then you can use the sys.set_int_max_str_digits() function to increase the limit and make your code work.

When you’re working with long integers, you can use the underscore character to make the literals more readable:

With the underscore as a thousands separator, you can make your integer literals more readable for fellow programmers reading your code.

You can also use other bases to represent integers. You can prepend the following characters to an integer value to indicate a base other than 10 :

Prefix Representation Base
or (Zero + b or B) Binary 2
or (Zero + o or O) Octal 8
or (Zero + x or X) Hexadecimal 16

Using the above characters, you can create integer literals using binary , octal , and hexadecimal representations. For example:

Note that the underlying type of a Python integer is always int . So, in all cases, the built-in type() function returns int , irrespective of the base you use to build the literal.

The built-in int type has a few methods that you can use in some situations. Here’s a quick summary of these methods:

Method Description
Returns a pair of integers whose ratio is equal to the original integer and has a positive denominator
Returns the number of ones in the binary representation of the absolute value of the integer
Returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros
Returns the integer represented by the given array of bytes
Returns an array of bytes representing an integer
Returns

When you call the .as_integer_ratio() method on an integer value, you get the integer as the numerator and 1 as the denominator. As you’ll see in a moment, this method is more useful in floating-point numbers.

Note that the int type also has a method called .is_integer() , which always returns True . This method exists for duck typing compatibility with floating-point numbers, which have the method as part of their public interface .

Note: To access an integer method on a literal, you need to wrap the literal in parentheses:

The parentheses are required because the dot character ( . ) also defines floating-point numbers, as you’ll learn in a moment. If you don’t use the parentheses, then you get a SyntaxError .

The .bit_count() and .bit_length() methods can help you when working on digital signal processing . For example, you may want every transmitted signal to have an even number of set bits:

In this toy example, you use .bit_count() to ensure that the received signal has the correct parity. This way, you implement a basic error detection mechanism.

Finally, the .from_bytes() and .to_bytes() methods can be useful in network programming. Often, you need to send and receive data over the network in binary format. To do this, you can use .to_bytes() to convert the message for network transmission. Similarly, you can use .from_bytes() to convert the message back.

The built-in int() function provides another way to create integer values using different representations. With no arguments, the function returns 0 :

This feature makes int() especially useful when you need a factory function for classes like defaultdict from the collections module.

Note: In Python, the built-in functions associated with data types, such as int() , float() , str() , and bytes() , are classes with a function-style name. The Python documentation calls them functions, so you’ll follow that practice in this tutorial. However, keep in mind that something like int() is really a class constructor rather than a regular function.

The int() function is commonly used to convert other data types into integers, provided that they’re valid numeric values:

In these examples, you first use int() to convert a floating-point number into an integer. Then, you convert a string into an integer. Note that when it comes to strings, you must ensure that the input string is a valid numeric value. Otherwise, you’ll get a ValueError exception.

Note: When you use the int() function to convert floating-point numbers, you must be aware that the function just removes the decimal or fractional part.

This function can take an additional argument called base , which defaults to 10 for decimal integers. This argument allows you to convert strings that represent integer values, which are expressed using a different base:

In this case, the first argument must be a string representing an integer value with or without a prefix. Then, you must provide the appropriate base in the second argument to run the conversion. Once you call the function, you get the resulting integer value.

Floating-Point Numbers

Floating-point numbers , or just float , are numbers with a decimal place. For example, 1.0 and 3.14 are floating-point numbers. You can also have negative float numbers, such as -2.75 . In Python, the name of the float class represents floating-point numbers:

In the following sections, you’ll learn the basics of how to create and work with floating-point numbers in Python.

The float type in Python designates floating-point numbers. To create these types of numbers, you can also use literals, similar to what you use in math. However, in Python, the dot character ( . ) is what you must use to create floating-point literals:

In these quick examples, you create floating-point numbers in three different ways. First, you have a literal build using an integer part, the dot, and the decimal part. You can also create a literal using the dot without specifying the decimal part, which defaults to 0 . Finally, you make a literal without specifying the integer part, which also defaults to 0 .

You can also have negative float numbers:

To create a negative floating-point number using a literal, you need to prepend the minus sign ( - ) to the number.

Similar to integer numbers, if you’re working with long floating-point numbers, you can use the underscore character as a thousands separator:

By using an underscore, you can make your floating-point literals more readable for humans, which is great.

Optionally, you can use the characters e or E followed by a positive or negative integer to express the number using scientific notation :

By using the e or E character, you can represent any floating-point number using scientific notation, as you did in the above examples.

Now, you can take a more in-depth look at how Python internally represents floating-point numbers. You can readily use floating-point numbers in Python without understanding them to this level, so don’t worry if this seems overly complicated. The information in this section is only meant to satisfy your curiosity.

Note: For additional information on the floating-point representation in Python and the potential pitfalls, see Floating Point Arithmetic: Issues and Limitations in the Python documentation.

Almost all platforms represent Python float values as 64-bit (double-precision) values, according to the IEEE 754 standard. In that case, a floating-point number’s maximum value is approximately 1.8 ⨉ 10 308 . Python will indicate this number, and any numbers greater than that, by the "inf" string:

The closest a nonzero number can be to zero is approximately 5.0 ⨉ 10 -324 . Anything closer to zero than that is effectively considered to be zero:

Python internally represents floating-point numbers as binary (base-2) fractions. Most decimal fractions can’t be represented exactly as binary fractions. So, in most cases, the internal representation of a floating-point number is an approximation of its actual value.

In practice, the difference between the actual and represented values is small and should be manageable. However, check out Make Python Lie to You for some challenges you should be aware of.

The built-in float type has a few methods and attributes which can be useful in some situations. Here’s a quick summary of them:

Method Description
Returns a pair of integers whose ratio is exactly equal to the original
Returns if the float instance is finite with integral value, and otherwise
Returns a representation of a floating-point number as a hexadecimal string
Builds the from a hexadecimal string

The .as_integer_ratio() method on a float value returns a pair of integers whose ratio equals the original number. You can use this method in scientific computations that require high precision. In these situations, you may need to avoid precision loss due to floating-point rounding errors.

For example, say that you need to perform computations with the gravitational constant:

With this exact ratio, you can perform calculations and prevent floating-point errors that may alter the results of your research.

The .is_integer() method allows you to check whether a given float value is an integer:

When the number after the decimal point is 0 , the .is_integer() method returns True . Otherwise, it returns False .

Finally, the .hex() and .fromhex() methods allow you to work with floating-point values using a hexadecimal representation:

The .hex() method returns a string that represents the target float value as a hexadecimal value. Note that .hex() is an instance method. The .fromhex() method takes a string that represents a floating-point number as an argument and builds an actual float number from it.

In both methods, the hexadecimal string has the following format:

In this template, apart from the integer identifier, the components are optional. Here’s what they mean:

  • sign defines whether the number is positive or negative. It may be either + or - . Only the - sign is required because + is the default.
  • "0x" is the hexadecimal prefix.
  • integer is a string of hexadecimal digits representing the whole part of the float number.
  • "." is a dot that separates the whole and fractional parts.
  • fraction is a string of hexadecimal digits representing the fractional part of the float number.
  • "p" allows for adding an exponent value.
  • exponent is a decimal integer with an optional leading sign.

With these components, you’ll be able to create valid hexadecimal strings to process your floating-point numbers with the .hex() and .fromhex() methods.

The built-in float() function provides another way to create floating-point values. When you call float() with no argument, then you get 0.0 :

Again, this feature of float() allows you to use it as a factory function.

The float() function also helps you convert other data types into float , provided that they’re valid numeric values:

In these examples, you first use float() to convert an integer number into a float. Then, you convert a string into a float. Again, with strings, you need to make sure that the input string is a valid numeric value. Otherwise, you get a ValueError exception.

Complex Numbers

Python has a built-in type for complex numbers . Complex numbers are composed of real and imaginary parts. They have the form a + bi , where a and b are real numbers, and i is the imaginary unit . In Python, you’ll use a j instead of an i . For example:

In this example, the argument to type() may look like an expression. However, it’s a literal of a complex number in Python. If you pass the literal to the type() function, then you’ll get the complex type back.

Note: To dive deeper into complex numbers, check out the Simplify Complex Numbers With Python tutorial.

In the following sections, you’ll learn the basics of creating complex numbers in Python. You’ll also explore the methods of this data type.

In Python, you can define complex numbers using literals that look like a + bj , where a is the real part, and bj is the imaginary part:

As you can conclude from these examples, there are many ways to create complex numbers using literals. The key is that you need to use the j letter in one of the components. Note that the j can’t be used alone. If you try to do so, you get a NameError exception because Python thinks that you’re creating an expression . Instead, you need to write 1j .

In Python, the complex type has a single method called .conjugate() . When you call this method on a complex number, you get the conjugate:

The conjugate() method flips the sign of the imaginary part, returning the complex conjugate .

You can also use the built-in complex() function to create complex numbers by providing the real and imaginary parts as arguments:

When you call complex() with no argument, you get 0j . If you call the function with a single argument, that argument is the real part, and the imaginary part will be 0j . If you want only the imaginary part, you can pass 0 as the first argument. Note that you can also use negative numbers. In general, you can use integers and floating-point numbers as arguments to complex() .

You can also use complex() to convert strings to complex numbers:

To convert strings into complex numbers, you must provide a string that follows the format of complex numbers. For example, you can’t have spaces between the components. If you add spaces, then you get a ValueError exception.

Finally, note that you can’t use strings to provide the imaginary part of complex numbers. If you do that, then you get a TypeError exception.

Strings and Characters

In Python, strings are sequences of character data that you can use to represent and store textual data. The string type in Python is called str :

In this example, the argument to type() is a string literal that you commonly create using double quotes to enclose some text.

Note: Check out the Strings and Character Data in Python tutorial to dive deeper into Python strings.

In the following sections, you’ll learn the basics of how to create, use, format, and manipulate strings in Python.

You can also use literals to create strings. To build a single-line string literal, you can use double ( "" ) or single quotes ( '' ) and, optionally, a sequence of characters in between them. All the characters between the opening and closing quotes are part of the string:

Python’s strings can contain as many characters as you need. The only limit is your computer’s memory.

You can define empty strings by using the quotes without placing characters between them:

An empty string doesn’t contain any characters, so when you use the built-in len() function with an empty string as an argument, you get 0 as a result.

There is yet another way to delimit strings in Python. You can create triple-quoted string literals, which can be delimited using either three single quotes or three double quotes. Triple-quoted strings are commonly used to build multiline string literals. However, you can also use them to create single-line literals:

Even though you can use triple-quoted strings to create single-line string literals, the main use case of them would be to create multiline strings. In Python code, probably the most common use case for these string literals is when you need to provide docstrings for your packages, modules , functions , classes , and methods .

What if you want to include a quote character as part of the string itself? Your first impulse might be to try something like this:

As you can see, that doesn’t work so well. The string in this example opens with a single quote, so Python assumes the next single quote—the one in parentheses—is the closing delimiter. The final single quote is then a stray, which causes the syntax error shown.

If you want to include either type of quote character within the string, then you can delimit the string with the other type. In other words, if a string is to contain a single quote, delimit it with double quotes and vice versa:

In these examples, your first string includes a single quote as part of the text. To do this, you use double quotes to delimit the literal. In the second example, you do the opposite.

Sometimes, you want Python to interpret a character or sequence of characters within a string differently. This may occur in one of two ways. You may want to:

  • Apply special meaning to characters
  • Suppress special character meaning

You can accomplish these goals by using a backslash ( \ ) character to indicate that the characters following it should be interpreted specially. The combination of a backslash and a specific character is called an escape sequence . That’s because the backslash causes the subsequent character to escape its usual meaning.

You already know that if you use single quotes to delimit a string, then you can’t directly embed a single quote character as part of the string because, for that string, the single quote has a special meaning —it terminates the string. You can eliminate this limitation by using double quotes to delimit the string.

Alternatively, you can escape the quote character using a backslash:

In this example, the backslash escapes the single quote character by suppressing its usual meaning. Now, Python knows that your intention isn’t to terminate the string but to embed the single quote.

The following is a table of escape sequences that cause Python to suppress the usual special interpretation of a character in a string:

Character Usual Interpretation Escape Sequence Escaped Interpretation
Delimit a string literal Literal single quote ( ) character
Delimit a string literal Literal double quote ( ) character
Terminates the input line Newline is ignored
Introduces an escape sequence Literal backslash ( ) character

You already have an idea of how the first two escape sequences work. Now, how does the newline escape sequence work? Usually, a newline character terminates a physical line of input. So, pressing Enter in the middle of a string will cause an error:

When you press Enter after typing Hello , you get a SyntaxError . If you need to break up a string over more than one line, then you can include a backslash before each new line:

By using a backslash before pressing enter, you make Python ignore the new line and interpret the whole construct as a single line.

Finally, sometimes you need to include a literal backslash character in a string. If that backslash doesn’t precede a character with a special meaning, then you can insert it right away:

In this example, the character after the backslash doesn’t match any known escape sequence, so Python inserts the actual backslash for you. Note how the resulting string automatically doubles the backslash. Even though this example works, the best practice is to always double the backslash when you need this character in a string.

However, you may have the need to include a backslash right before a character that makes up an escape sequence:

Because the sequence \" matches a known escape sequence, your string fails with a SyntaxError . To avoid this issue, you can double the backslash:

In this update, you double the backslash to escape the character and prevent Python from raising an error.

Note: When you use the built-in print() function to print a string that includes an escaped backslash, then you won’t see the double backslash in the output:

In this example, the output only displays one backslash, producing the desired effect.

Up to this point, you’ve learned how to suppress the meaning of a given character by escaping it. Suppose you need to create a string containing a tab character. Some text editors may allow you to insert a tab character directly into your code. However, this is considered a poor practice for several reasons:

  • Computers can distinguish between tabs and a sequence of spaces, but human beings can’t because these characters are visually indistinguishable.
  • Some text editors automatically eliminate tabs by expanding them to an appropriate number of spaces.
  • Some Python REPL environments will not insert tabs into code.

In Python, you can specify a tab character by the \t escape sequence:

The \t escape sequence changes the usual meaning of the letter t . Instead, Python interprets the combination as a tab character.

Here is a list of escape sequences that cause Python to apply special meaning to some characters instead of interpreting them literally:

Escape Sequence Escaped Interpretation
ASCII Bell ( ) character
ASCII Backspace ( ) character
ASCII Formfeed ( ) character
ASCII Linefeed ( ) character
Character from Unicode database with given
ASCII Carriage return ( ) character
ASCII Horizontal tab ( ) character
Unicode character with 16-bit hex value
Unicode character with 32-bit hex value
ASCII Vertical tab ( ) character
Character with octal value
Character with hex value

Of these escape sequences, the newline or linefeed character ( \n ) is probably the most popular. This sequence is commonly used to create nicely formatted text outputs.

Here are a few examples of the escape sequences in action:

These escape sequences are typically useful when you need to insert characters that aren’t readily generated from the keyboard or aren’t easily readable or printable.

A raw string is a string that doesn’t translate the escape sequences. Any backslash characters are left in the string.

Note: To learn more about raw strings, check out the What Are Python Raw Strings? tutorial.

To create a raw string, you can precede the literal with an r or R :

The raw string suppresses the meaning of the escape sequence and presents the characters as they are. This behavior comes in handy when you’re creating regular expressions because it allows you to use several different characters that may have special meanings without restrictions.

Python has another type of string literal called formatted strings or f-strings for short. F-strings allow you to interpolate values into your strings and format them as you need.

Note: To dive deeper into f-strings, check out the Python’s F-String for String Interpolation and Formatting tutorial

To build f-string literals, you must prepend an f or F letter to the string literal. Because the idea behind f-strings is to interpolate values and format them into the final string, you need to use something called a replacement field in your string literal. You create these fields using curly brackets.

Here’s a quick example of an f-string literal:

In this example, you interpolate the variable name into your string using an f-string literal and a replacement field.

You can also use f-strings to format the interpolated values. To do that, you can use format specifiers that use the syntax defined in Python’s string format mini-language . For example, here’s how you can present numeric values using a currency format:

Inside the replacement field, you have the variable you want to interpolate and the format specifier, which is the string that starts with a colon ( : ). In this example, the format specifier defines a floating-point number with two decimal places.

Python’s str data type is probably the built-in type with the most available methods . In fact, you’ll find methods for most string processing operations. Here’s a summary of the methods that perform some string processing and return a transformed string object:

Method Description
Converts the first character to uppercase and the rest to lowercase
Converts the string into lowercase
Centers the string between using
Encodes the string using the specified
Replaces tab characters with spaces according to
Interpolates and formats the specified values
Interpolates and formats the specified values using a dictionary
Joins the items in an iterable with the string as a separator
Returns a left-justified version of the string
Returns a right-justified version of the string
Converts the string into lowercase
Trims the string by removing from the beginning and end
Trims the string by removing from the beginning
Trims the string by removing from the end
Removes from the beginning of the string
Removes from the end of the string
Returns a string where the substring is replaced with
Converts lowercase letters to uppercase letters and vice versa
Converts the first character of each word to uppercase and the rest to lowercase
Converts a string into uppercase
Fills the string with a specified number of zeroes at the beginning

All the above methods allow you to perform a specific transformation on an existing string. In all cases, you get a new string as a result:

As you can see, the methods in these examples perform a specific transformation on the original string and return a new string object.

You’ll also find that the str class has several Boolean-valued methods or predicate methods:

Method Result
if the string ends with the specified suffix, otherwise
if the string starts with the specified prefix, otherwise
if all characters in the string are alphanumeric, otherwise
if all characters in the string are letters, otherwise
if the string is empty or all characters in the string are ASCII, otherwise
if all characters in the string are decimals, otherwise
if all characters in the string are digits, otherwise
if the string is a valid Python name, otherwise
if all characters in the string are lowercase, otherwise
if all characters in the string are numeric, otherwise
if all characters in the string are printable, otherwise
if all characters in the string are whitespaces, otherwise
if the string follows title case, otherwise
if all characters in the string are uppercase, otherwise

All these methods allow you to check for various conditions in your strings. Here are a few demonstrative examples:

In these examples, the methods check for specific conditions in the target string and return a Boolean value as a result.

Finally, you’ll find a few other methods that allow you to run several other operations on your strings:

Method Description
Returns the number of occurrences of a substring
Searches the string for a specified value and returns the position of where it was found
Searches the string for a specified value and returns the last position of where it was found
Searches the string for a specified value and returns the position of where it was found
Searches the string for a specified value and returns the last position of where it was found
Splits the string at the specified separator and returns a list
Splits the string at line breaks and returns a list
Splits the string at the first occurance of
Splits the string at the last occurance of
Splits the string at the specified separator and returns a list
Returns a translation table to be used in translations
Returns a translated string

The first method counts the number of repetitions of a substring in an existing string. Then, you have four methods that help you find substrings in a string.

The .split() method is especially useful when you need to split a string into a list of individual strings using a given character as a separator, which defaults to whitespaces. You can also use .partition() or .rpartition() if you need to divide the string in exactly two parts:

In these toy examples, you’ve used the .split() method to build a list of words from a sentence. Note that by default, the method uses whitespace characters as separators. You also used .partition() and .rpartition() to separate out the first and last number from a string with numbers.

The .maketrans() and .translate() are nice tools for playing with strings . For example, say that you want to implement the Cesar cipher algorithm . This algorithm allows for basic text encryption by shifting the alphabet by a number of letters. For example, if you shift the letter a by three, then you get the letter d , and so on.

The following code implements cipher() , a function that takes a character and rotates it by three:

In this example, you use .maketrans() to create a translation table that matches the lowercase alphabet to a shifted alphabet. Then, you apply the translation table to a string using the .translate() method.

Python’s strings are sequences of characters. As other built-in sequences like lists and tuples , strings support a set of operations that are known as common sequence operations . The table below is a summary of all the operations that are common to most sequence types in Python:

Operation Example Result
The length of
The item at index
A slice of from index to
A slice of from index to with step
The smallest item of
The largest item of
if an item of is equal to , else
if an item of is equal to , else
The concatenation of and
or The repetition of a number of times specified by
The index of the first occurrence of in
The total number of occurrences of in

Sometimes, you need to determine the number of characters in a string. In this situation, you can use the built-in len() function:

When you call len() with a string as an argument, you get the number of characters in the string at hand.

Another common operation you’d run on strings is retrieving a single character or a substring from an existing string. In these situations, you can use indexing and slicing, respectively:

To retrieve a character from an existing string, you use the indexing operator [index] with the index of the target character. Note that indices are zero-based, so the first character lives at index 0 .

To retrieve a slice or substring from an existing string, you use the slicing operator with the appropriate indices. In the example above, you don’t provide the start index i , so Python assumes that you want to start from the beginning of the string. Then, you give the end index j to tell Python where to stop the slicing.

You can take a leap and try the rest of the operations by yourself. It will be a great learning exercise!

When it comes to creating and working with strings, you have two functions that can help you out and make your life easier:

The built-in str() function allows you to create new strings and also convert other data types into strings:

In these examples, you use the str() function to convert objects from different built-in types into strings. In the first example, you use the function to create an empty string. In the other examples, you get strings consisting of the object’s literals between quotes, which provide user-friendly representations of the objects.

At first glance, these results may not seem useful. However, there are use cases where you need to use str() .

For example, say that you have a list of numeric values and want to join them using the str.join() method. This method only accepts iterables of strings, so you need to convert the numbers:

If you try to pass a list of numeric values to .join() , then you get a TypeError exception because the function only joins strings. To work around this issue, you use a generator expression to convert each number to its string representation.

Behind the str() function, you’ll have the .__str__() special method . In other words, when you call str() , Python automatically calls the .__str__() special method on the underlying object. You can use this special method to support str() in your own classes.

Consider the following Person class:

In this class, you have two instance attributes , .name and .age . Then, you have .__str__() special methods to provide user-friendly string representations for your class.

Here’s how this class works:

In this code snippet, you create an instance of Person . Then, you call str() using the object as an argument. As a result, you get a descriptive message back, which is the user-friendly string representation of your class.

Note: To learn more about objects’ string representations in Python, check out the When Should You Use .__repr__() vs .__str__() in Python? tutorial.

Similarly, when you pass an object to the built-in repr() function, you get a developer-friendly string representation of the object itself:

In the case of built-in types, the string representation you get with repr() is the same as the one you get with the str() function. This is because the representations are the literals of each object, and you can directly use them to re-create the object at hand.

Ideally, you should be able to re-create the current object using this representation. To illustrate, go ahead and update the Person class:

The .__repr__() special method allows you to provide a developer-friendly string representation for your class:

You should be able to copy and paste the resulting representation to re-create the object. That’s why this string representation is said to be developer-friendly.

Bytes and Bytearrays

Bytes are immutable sequences of single bytes. In Python, the bytes class allows you to build sequences of bytes. This data type is commonly used for manipulating binary data, encoding and decoding text, processing file input and output, and communicating through networks.

Python also has a bytearray class as a mutable counterpart to bytes objects:

In the following sections, you’ll learn the basics of how to create and work with bytes and bytearray objects in Python.

To create a bytes literal, you’ll use a syntax that’s largely the same as that for string literals. The difference is that you need to prepend a b to the string literal. As with string literals, you can use different types of quotes to define bytes literals:

There is yet another difference between string literals and bytes literals. To define bytes literals, you can only use ASCII characters. If you need to insert binary values over the 127 characters, then you have to use the appropriate escape sequence:

In this example, \xc3\xb1 is the escape sequence for the letter ñ in the Spanish word "España" . Note that if you try to use the ñ directly, you get a SyntaxError .

The built-in bytes() function provides another way to create bytes objects. With no arguments, the function returns an empty bytes object:

You can use the bytes() function to convert string literals to bytes objects:

In these examples, you first use bytes() to convert a string into a bytes object. Note that for this to work, you need to provide the appropriate character encoding . In this example, you use the UTF-8 encoding. If you try to convert a string literal without providing the encoding, then you get a TypeError exception.

You can also use bytes() with an iterable of integers where each number is the Unicode code point of the individual characters:

In this example, each number in the list you use as an argument to bytes() is the code point for a specific letter. For example, 65 is the code point for A , 66 for B , and so on. You can get the Unicode code point of any character using the built-in ord() function.

Python doesn’t have dedicated literal syntax for bytearray objects. To create them, you’ll always use the class constructor bytearray() , which is also known as a built-in function in Python. Here are a few examples of how to create bytearray objects using this function:

In the first example, you call bytearray() without an argument to create an empty bytearray object. In the second example, you call the function with an integer as an argument. In this case, you create a bytearray with five zero-filled items.

Next, you use a list of code points to create a bytearray . This call works the same as with bytes objects. Finally, you use a bytes literal to build up the bytearray object.

In Python, bytes and bytearray objects are quite similar to strings. Instead of being sequences of characters, bytes and bytearray objects are sequences of integer numbers, with values from 0 to 255 .

Because of their similarities with strings, the bytes and bytearray types support mostly the same methods as strings , so you won’t repeat them in this section. If you need detailed explanations of specific methods, then check out the Bytes and Bytearray Operations section in Python’s documentation.

Finally, both bytes and bytearray objects support the common sequence operations that you learned in the Common Sequence Operations on Strings section.

Boolean logic relies on the truth value of expressions and objects. The truth value of an expression or object can take one of two possible values: true or false . In Python, these two values are represented by True and False , respectively:

Both True and False are instances of the bool data type, which is built into Python. In the following sections, you’ll learn the basics about Python’s bool data type.

Python provides a built-in Boolean data type. Objects of this type may have one of two possible values: True or False . These values are defined as built-in constants with values of 1 and 0 , respectively. In practice, the bool type is a subclass of int . Therefore, True and False are also instances of int :

In Python, the bool type is a subclass of the int type. It has only two possible values, 0 and 1 , which map to the constants False and True .

These constant values are also the literals of the bool type:

Boolean objects that are equal to True are truthy, and those equal to False are falsy. In Python, non-Boolean objects also have a truth value. In other words, Python objects are either truthy or falsy.

You can use the built-in bool() function to convert any Python object to a Boolean value. Internally, Python uses the following rules to identify falsy objects:

  • Constants that are defined to be false: None and False
  • The zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1)
  • Empty sequences and collections: '' , () , [] , {} , set() , range(0)

The rest of the objects are considered truthy in Python. You can use the built-in bool() function to explicitly learn the truth value of any Python object:

In these examples, you use bool() with arguments of different types. In each case, the function returns a Boolean value corresponding to the object’s truth value.

Note: You rarely need to call bool() yourself. Instead, you can rely on Python calling bool() under the hood when necessary. For example, you can say if numbers: instead of if bool(numbers): to check whether numbers is truthy.

You can also use the bool() function with custom classes:

By default, all instances of custom classes are true. If you want to modify this behavior, you can use the .__bool__() special method. Consider the following update of your Point class:

The .__bool__() method returns False when both coordinates are equal to 0 and True otherwise. Here’s how your class works now:

Now, when both coordinates are 0 , you get False from calling bool() . For the rest of the points, you get True .

You’ve learned about the basic built-in data types that Python provides. These types are the building blocks of most Python programs. With them, you can represent numeric, textual, byte, and Boolean data.

In this tutorial, you’ve learned about:

  • Python’s numeric types, such as int , float , and complex
  • The str data type, which represents textual data in Python
  • Boolean values with Python’s bool data type

With this knowledge, you’re ready to start using all of the basic data types that are built into Python.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Recommended Video Course: Basic Data Types in Python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Basic Data Types in Python: A Quick Exploration (Sample Code)

🔒 No spam. We take your privacy seriously.

assignment data type

  • PHOENIXNAP HOME
  • Colocation Overview
  • Data Center as a Service Solutions for Digital Transformation
  • Hardware as a Service Flexible Hardware Leasing
  • Meet-Me Room The Interconnectivity Hub
  • Schedule a Tour Guided Virtual Data Center Tour
  • Data Center Locations Global Data Center Footprint
  • Platform Overview
  • Rancher Deployment One-Click Kubernetes Deployment
  • Intel Xeon E-2300 Entry-Level Servers
  • 4th Gen Intel Xeon Scalable CPUs Boost Data-Intensive Workloads
  • Alliances Technology Partnerships
  • Object Storage S3-Compatible Storage Solution
  • Dedicated Servers Overview
  • FlexServers Vertical CPU Scaling
  • Intel Xeon-E Servers Intel Xeon 2200 Microarchitecture
  • GPU Servers Servers with NVIDIA Tesla GPUs
  • Dedicated Servers vs. BMC Compare Popular Platforms
  • Promotions See Available Discounts
  • Buy Now See All Servers
  • Managed Private Cloud (MPC) Highly Customizable Cloud
  • Data Security Cloud Secure-By-Design Cloud
  • Hybrid Cloud Multi-Platform Environment
  • Edge Computing Globally Distributed Servers
  • Object Storage S3 API Compatible Storage Service
  • Bare Metal Cloud API-Driven Dedicated Servers
  • Alternative Cloud Provider Overcome Public Cloud Limitations
  • Backup Solutions Veeam-Powered Services
  • Disaster Recovery VMware, Veeam, Zerto
  • Veeam Cloud Connect Backup and Replication
  • Managed Backup for Microsoft 365 Veeam-Powered Service
  • Data Security Cloud Secure-by-Design Cloud
  • Encryption Management Platform (EMP) Cryptographic Key Management
  • Confidential Computing Data-in-Use Encryption
  • Ransomware Protection Data Protection and Availability
  • DDoS Protection Network Security Features
  • CONTACT SUPPORT
  • Network Overview Global Network Footprint
  • Network Locations U.S., Europe, APAC, LATAM
  • Speed Test Download Speed Test
  • Blog IT Tips and Tricks
  • Glossary IT Terms and Definitions
  • Resource Library Knowledge Resources
  • Events Let's Meet!
  • Newsroom Media Library
  • Developers Development Resources Portal
  • APIs Access Our Public APIs
  • GitHub Public Code Repositories
  • Search for:

Python Data Types {Comprehensive Overview}

Home » DevOps and Development » Python Data Types {Comprehensive Overview}

Introduction

Every programming language has built-in data types, including Python. Data types provide information about the different kinds of variables and dictate the programming flow. Other libraries often create their data types, such as DataFrames in Pandas .

Choosing the correct data type depends on the problem at hand. It is best to start by getting to know Python's basic types of data and their use cases.

Learn about the different Python data types and when to use them through examples in this tutorial.

Python Data Types

Basic Data Types in Python

A data type is a characteristic that tells the compiler (or interpreter) how a programmer intends to use the data. There are two general categories of data types, differing whether the data is changeable after definition:

1. Immutable . Data types that are not changeable after assignment.

2. Mutable . Data types that are changeable after assignment.

Note : Variable IDs change when changing data for immutable types, whereas mutable types retain the same variable ID after the change. Check the variable ID with the built-in function id(<variable>) .

Variables store different types of data. Creating a variable of a particular data type creates an object of a data type class. The Python interpreter automatically assumes a type when creating a variable.

Python Data Types Overview

The data type of any object is found using the built-in type() function. The output shows the name of the class for the given object.

Note: Learn about Python static method that performs a task in isolation from the class.

Numeric Type

Numeric type objects represent number values. They are divided into three subgroups:

  • Floating Point Numbers

Complex Numbers

Integer values belong to the int class. Specifically, integers represent positive or negative whole numbers without a decimal. Some examples of integers include:

Examples of Python integers

Integers have unlimited precision. There is no distinction between long and short numbers. The length depends on the computer memory:

Very long integer in Python

Binary, octal and hexadecimal number bases also evaluate to integers:

Integers of different bases

Printing the values converts to their base ten forms automatically.

Note : One key skill in writing code with Python is the ability to use comments. Comments are usually used to leave notes about the function of the code. However, they can also be used to disable parts of the code. Learn how to comment in Python effectively.

Floating-Point Numbers

Floating-point numbers in Python are numbers defined with a decimal point. The class type is float . For instance:

Examples of floating-point numbers in Python

Internally, they are binary fractions, which means the number approximates the decimal counterpart. The difference between the real and the approximated value is often unnoticeable. Rounding the value yields the exact number. For example:

Floating-point evaluation example

Alternatively, a number with the character E followed by a number indicates scientific notation:

Scientific notation of floating-point numbers

Scientific notation belongs to the floating-point class of numbers as well. The syntax accepts both lowercase e as well as uppercase E .

Floating-point numbers after 1.79×10 308 evaluate to infinity. The smallest non-zero number is 5.0×10 -324 . Smaller numbers evaluate to zero:

Edge cases of Python floating-point numbers

The values correspond to 64-bit double-precision values.

Complex numbers are often used in mathematical sciences. Python provides a class for complex numbers called complex . To write complex numbers, use:

Alternatively, you can omit the real part:

For example:

Examples of complex numbers in Python

The output shows the data belongs to the complex class.

Note : Check out our SciPy tutorial to learn about scientific computing in Python using the SciPy library.

Sequence Type

Sequence types help represent sequential data stored into a single variable. There are three types of sequences used in Python:

Individual sequence types differ from one another when it comes to changeability and order.

Strings are a sequence of bytes representing Unicode characters. The string type in Python is called str .

Create a String

Depending on the use case and characters needed, there are four different ways to create a string. They differ based on the delimiters and whether a string is single or multiline.

1. Create a string by using double quote delimiters :

A string delimited with double quotes is helpful for strings containing single quotes or apostrophes. Alternatively, you can use escape characters:

String with double quote delimiters

The example additionally shows how to display the backslash character in a string.

2. Create a string by using single quote delimiters :

Python strings delimited by single quotes are valid when a string contains a double quote. Another way is to use escape characters. For instance:

String with single quote delimiters

There are two ways to delimit a multiline string.

a) Create a multiline string by using triple single quote delimiters :

Multiline string with triple single quote delimiters

Use the triple single quotes to delimit a string if it contains both single, double, triple double quotes or ends in a double quote.

b) Create a string by using triple double quote delimiters :

Multiline string with triple double quote delimiters

Use the triple double quote delimiter for strings containing single, double, triple single quotes or strings ending in a single quote.

Note: Learn how to substring a string in Python .

Access Elements of a String

Strings in Python are arrays of characters. To access individual elements, use indexing:

Access elements of a string

To access parts of a string, use string slicing :

String slicing

Access the first element at index 0. Counting backward starting from -1 accesses the end of a sequence.

Since strings are arrays, you can loop through all the characters by using a for loop:

Looping through a string

The code prints all letters of a string one by one.

A Python list is an ordered changeable array. Lists allow duplicate elements regardless of their type. Adding or removing members from a list allows changes after creation.

Create a List

Create a list in Python by using square brackets , separating individual elements with a comma:

Example of a List in Python

Make a nested list by adding a list to a list:

Example of a nested list

Since Python lists are changeable, they allow creating empty lists and appending elements later, as well as adding or removing members to an existing list.

Access Elements of a List

Lists are a sequence of elements. Access members by using indexing notation, where the first element is at index 0:

Access elements of a list

Slicing a list returns all the elements between two indexes:

List slicing

Negative indexes are also possible:

Negative indexing in a list

The -1 index prints the last element in the list. Negative indexing is especially useful for navigating to the end of a long list of members.

Note: Learn how to find the list length in Python .

Python Tuples are an array of unchangeable ordered elements. Once a tuple is stored into a variable, members cannot be added or removed. A tuple allows duplicate members of any type.

Create a Tuple

To create a tuple, use the standard round brackets, separating individual elements with a comma:

Example of a Tuple in Python

Make a nested tuple by adding a tuple to a tuple:

Example of a Nested tuple

To create a tuple with a single element, use a comma after the first element:

Tuple with one element

Without a comma, the variable is a string.

Create an empty tuple using the round brackets without elements. Although it seems redundant since tuples are unchangeable, an empty tuple helps indicate a lack of data in certain use cases.

Access Elements of a Tuple

Tuples support indexing notation. Access individual elements by using square brackets and the index of the element:

Access elements of a tuple

Negative indexing allows accessing elements at the end of the list.

To access parts of a tuple, use slicing notation:

Tuple slicing

The output shows the third and fourth elements of the tuple.

Boolean Type

Boolean data types belong to the bool class and determine the truth value of expressions. Objects of the Boolean type evaluate either to True or False :

Examples of boolean types in Python

Booleans are a subtype of integer values. Checking the truth value of integers 1 and 0 with True and False returns true in both cases:

Boolean aliases

The data type of the values is different. True and False are both Boolean types, whereas 1 and 0 are integer types.

The Set data type is part of the set class. It stores data collections into a single variable. Sets are unordered and do not allow access to individual elements through indexing. Any duplicate values are ignored.

To create a set, use the curly brackets notation and separate individual elements with a comma:

Example of a Set in Python

Notice the multiple instances of data disappear.

Mapping Type

Mapping data type is represented by a Python dictionary . A dictionary is a collection of data with key and value pairs belonging to the dict class.

To create a dictionary, use the curly bracket notation and define the key value pairs. For example:

Example of a Dictionary in Python

The key and value pairs accept any data type. To access a value in a dictionary, use the key as index:

Accessing value of a dictionary using a key

Dictionaries come in handy when storing linked data pairs.

Note: Learn what causes "python: command not found" error and what to do to fix it.

Managing Data Types in Python

When writing lengthy and complex programs, managing different data types becomes a crucial aspect of tackling programming problems. It is impossible to predict the needed data type flawlessly. However, knowing how to check or change a data type is essential to programming.

Check Data Type

Every variable has a data type, which is checked with the built-in function type() :

Checking the type of data

The example above shows several ways to write the number 1 using various data types. The function type() also works on variables.

Set Data Type

The data type in Python is set automatically when writing a value to a variable. The class constructor for each data type allows setting the specific data type of a variable as well:

String
Integer
Floating-point
Complex
List
Tuple
Boolean
Set
Dictionary

Convert Data Type

Some Python data types are convertible to other data types. There are two ways to convert a variable type:

  • Explicitly . The class constructor for data types converts data types as well.
  • Implicitly . When possible, the Python interpreter automatically converts a data type - for example, adding an integer to a float yields a float result.

Note: Python supports various methods for analyzing and resolving unaccounted data. Learn more in our guide Handling Missing Data in Python: Causes and Solutions .

Python provides many built-in data types depending on the use and function of the data stored. Since data types are classes, creating new data types is not a complicated process.

When programming in Python, both IDEs and Code Editors are useful. Knowing the difference between all the available options and when to use them is crucial for efficient development.

For further reading, learn about the MySQL data types .

assignment data type

Variable Data Types Explained

Deborah Kurata

Walking into a hardware store, it's not enough to say: "I need a tool". You need to be specific about the type of tool you need.

Each tool type has its particular purpose: A hammer to drive a nail into wood, a paint brush to paint, and a wrench tightens or loosens nuts and bolts.

The same goes for the variables we use to hold data in our code. Regardless of the programming language you use, when building a website or app you'll want to use the appropriate type of variable for a particular purpose. We'll look at basic types and more complex types such as arrays (lists) and objects.

You can also watch the associated video here which walks through the key variable data types.

Basic Data Types

The most common basic data types available in most programming languages include:

numbers : we use this for any data that is numeric or should be worked with as a number for addition or other math operations.

In some programming languages, there are multiple data types for numbers, depending on whether the number is an integer, decimal, or currency, for example.

If we were building a number guessing game, we would hold the guessed number in a numeric data type, like this:

string : we use this for any data that is text. For example, a name or address or message. In most programming languages, strings require quotes. Notice that the text inside of the quotes can include spaces and other special characters.

date : we use this for data that is a date or time, such as a birthday.

Boolean : we use this for data that only has the value true or false . In a number guessing game, the user's guess was either correct or it wasn't. There is no other value.

For programming languages that are considered to be "strongly typed", such as C# and TypeScript, the data type defines the kind of data that can be assigned to that variable. You'll see an error if you try to put the wrong type of data into a variable.

With "dynamically typed" languages such as JavaScript and Python, the data type defines the kind of data currently assigned to that variable. That type can change if you put a different type of data into that variable. So the type dynamically changes based on the currently assigned value.

Array (List) Data Type

Another important data type in programming is an array, which in some programming languages is called a list.

Let's say we add a feature to our website or app so the user can provide the name of each of their pets. We could hold each name in a separate variable like shown in Figure 1.

Pictures of three cats with three variables to hold the name of each cat.

But we'd then have to limit how many pets we could allow based on how many variables we'd defined.

Arrays solve this problem. An array is a collection or set of data items. You can think of an array as a list of items.

The data items in an array are often of the same type, so you may have an array of numbers, of strings, or of dates.

In some programming languages, including C#, TypeScript, JavaScript, and Python, arrays are defined with square brackets: [ ] and each value in the array is separated with commas.

Here we define an array of strings. Recall that strings must be enclosed in quotation marks.

Pictures of three cats with a single array to hold the name of each cat.

With arrays, the user can have an almost limitless number of items, such as names, because we can keep appending to the array.

Object Data Type (Custom Data Type)

What about data that represent things in our application? Things like those shown in Figure 3:

  • Or post, and I actually mean a social media post here, but close enough.

Four icons representing pet, customer, product, and post

We can hold detailed information about a thing, such as a pet or customer or blog post, in a set of string, number, and date variables. But to keep that set of variables for a particular thing together as one variable, we want a custom data type that describes that thing.

Think of an object as a custom data type that groups a set of related variables for a particular thing.

Let's walk through how to define an object as a custom data type.

Step 1: Identify Properties (Characteristics)

To define an object data type, we first identify the data we want to hold for the object. These are often characteristics of the object, like a pet's name, type, and age. In programming, we call each of these characteristics a property of the object.

Let's look at some examples.

Four icons representing pet, customer, product, and post and their characteristics

For a customer, the properties might be the customer's name, shipping address, and default payment method.

A product may have a product name, description, and a Boolean value defining whether the product is currently in stock.

And for a blog post, we may want to hold the user's name, the post text, and the date.

Each of these are properties of our object.

At this point, we have the list of properties for the object. We want to hold data for each of these properties.

Step 2: Assign a Property Name

Once we have the properties defined, we assign a name to each property as shown in Figure 5.

Four icons representing pet, customer, product, and post and their property names

The names follow the conventions for the programming language you are using. In general, property names cannot have spaces or special characters in them. They are often defined using camel case, with the first letter lower case and each additional word capitalized.

Each property also has a basic data type. petName , customerName , productName , and userName are strings. age is a number, inStock is a Boolean value (true or false), and postDate is a date.

We could keep track of separate variables for each of these pet properties and each of these customer properties and each of these post properties. But we'd end up with lots of unorganized variables.

Let's instead group each set of related properties into an object.

Step 3: Group the Properties for the Object

We group the properties of an object together using object literal syntax. This keeps the data for an object together and makes it easier to work with it as a set.

The syntax used to group the properties depends on the programming language you use. In languages such as JavaScript, TypeScript, and C#, object properties are grouped within curly braces ({ }).

Four icons representing pet, customer, product, and post and a sample object.

For each object, the variable on the left of the equal sign is the object variable and represents a specific pet, customer, product, or post. On the right of the equal sign, inside the curly braces, we list each property name, a colon, and the data (often called a value). We separate properties with a comma.

To say that another way, you can think of an object as a collection of name and value pairs. The name is the property name and the value is the data you want to store for that property.

In Figure 6, we defined a pet object with a specific set of properties, and a value for each property. Same with the customer, and so on.

Try It Yourself!

Let's stop here for a moment and think about objects. What's your favorite hobby? If you built a website or an app to support that hobby, what objects might you define?

Maybe you like to bake, so you'd build a recipe app with your favorite recipes. You work with the data for each recipe using an object with properties such as ingredients, recipe steps, baking temperature, and time.

Or say you like sports. You'd track the data for each player using an object with properties such as name, position, and stats. And you'd track the data for each game using another object with properties such as teams and score.

What objects did you define for your hobby?

Wrapping Up

A variable has a data type such as number, string (for text), date, and Boolean (for true or false).

An array stores a set of data items, often of the same type.

An object represents something in the website or app, like a pet, a customer, or a blog post. The object groups related properties holding the data for the object.

Now that you know all about data types, you can create variables of the appropriate type to hold any data you need for your website or app.

If you are self-taught or new to programming and want more information about general programming concepts, check out this course:

Deborah Kurata is a software developer, YouTube content creator, speaker, and Pluralsight author. Her focus includes: web development, Angular, RxJS, GitHub, and C#. She is an MVP and GDE.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

pandas.DataFrame.assign #

Assign new columns to a DataFrame.

Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten.

The column names are keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas doesn’t check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned.

A new DataFrame with the new columns in addition to all the existing columns.

Assigning multiple columns within the same assign is possible. Later items in ‘**kwargs’ may refer to newly created or modified columns in ‘df’; items are computed and assigned into ‘df’ in order.

Where the value is a callable, evaluated on df :

Alternatively, the same behavior can be achieved by directly referencing an existing Series or sequence:

You can create multiple columns within the same assign where one of the columns depends on another one defined within the same assign:

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Expressions and operators

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely evaluate .

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to 7 .

The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7 . However, if it's not eventually part of a bigger construct (for example, a variable declaration like const z = 3 + 4 ), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.

As the examples above also illustrate, all complex expressions are joined by operators , such as = and + . In this section, we will introduce the following operators:

Assignment operators

Comparison operators, arithmetic operators, bitwise operators, logical operators, bigint operators, string operators, conditional (ternary) operator, comma operator, unary operators, relational operators.

These operators join operands either formed by higher-precedence operators or one of the basic expressions . A complete and detailed list of operators and expressions is also available in the reference .

The precedence of operators determines the order they are applied when evaluating an expression. For example:

Despite * and + coming in different orders, both expressions would result in 7 because * has precedence over + , so the * -joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3 + 4 or x * y . This form is called an infix binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x . The operator operand form is called a prefix unary operator, and the operand operator form is called a postfix unary operator. ++ and -- are the only postfix operators in JavaScript — all other operators, like ! , typeof , etc. are prefix.

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Name Shorthand operator Meaning

Assigning to properties

If an expression evaluates to an object , then the left-hand side of an assignment expression may make assignments to properties of that expression. For example:

For more information about objects, read Working with Objects .

If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:

In strict mode , the code above throws, because one cannot assign properties to primitives.

It is an error to assign values to unmodifiable properties or to properties of an expression without properties ( null or undefined ).

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

Without destructuring, it takes multiple statements to extract values from arrays and objects:

With destructuring, you can extract multiple values into distinct variables using a single statement:

Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with const , let , or var ) or as standalone statements.

However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this result value is usually not used, it can then be used by another expression.

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, some JavaScript style guides discourage chaining or nesting assignments . Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.

By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be logged, it can be put inside an array literal or function call, and so on.

The evaluation result matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that x = f() evaluates into whatever f() 's result is, x += f() evaluates into the resulting sum x + f() , x **= f() evaluates into the resulting power x ** f() , and so on.

In the case of logical assignments, x &&= f() , x ||= f() , and x ??= f() , the return value is that of the logical operation without the assignment, so x && f() , x || f() , and x ?? f() , respectively.

When chaining these expressions without parentheses or other grouping operators like array literals, the assignment expressions are grouped right to left (they are right-associative ), but they are evaluated left to right .

Note that, for all assignment operators other than = itself, the resulting values are always based on the operands' values before the operation.

For example, assume that the following functions f and g and the variables x and y have been declared:

Consider these three examples:

Evaluation example 1

y = x = f() is equivalent to y = (x = f()) , because the assignment operator = is right-associative . However, it evaluates from left to right:

  • The y on this assignment's left-hand side evaluates into a reference to the variable named y .
  • The x on this assignment's left-hand side evaluates into a reference to the variable named x .
  • The function call f() prints "F!" to the console and then evaluates to the number 2 .
  • That 2 result from f() is assigned to x .
  • The assignment expression x = f() has now finished evaluating; its result is the new value of x , which is 2 .
  • That 2 result in turn is also assigned to y .
  • The assignment expression y = x = f() has now finished evaluating; its result is the new value of y – which happens to be 2 . x and y are assigned to 2 , and the console has printed "F!".

Evaluation example 2

y = [ f(), x = g() ] also evaluates from left to right:

  • The y on this assignment's left-hand evaluates into a reference to the variable named y .
  • The function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 result from g() is assigned to x .
  • The assignment expression x = g() has now finished evaluating; its result is the new value of x , which is 3 . That 3 result becomes the next element in the inner array literal (after the 2 from the f() ).
  • The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with two values: [ 2, 3 ] .
  • That [ 2, 3 ] array is now assigned to y .
  • The assignment expression y = [ f(), x = g() ] has now finished evaluating; its result is the new value of y – which happens to be [ 2, 3 ] . x is now assigned to 3 , y is now assigned to [ 2, 3 ] , and the console has printed "F!" then "G!".

Evaluation example 3

x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For more information about objects, read Working with Objects .)

  • The x in this property access evaluates into a reference to the variable named x .
  • Then the function call f() prints "F!" to the console and then evaluates to the number 2 .
  • The x[f()] property access on this assignment has now finished evaluating; its result is a variable property reference: x[2] .
  • Then the function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 is now assigned to x[2] . (This step will succeed only if x is assigned to an object .)
  • The assignment expression x[f()] = g() has now finished evaluating; its result is the new value of x[2] – which happens to be 3 . x[2] is now assigned to 3 , and the console has printed "F!" then "G!".

Avoid assignment chains

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, chaining assignments in the same statement is discouraged .

In particular, putting a variable chain in a const , let , or var statement often does not work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are not declared by the const / let / var statement. For example:

This statement seemingly declares the variables x , y , and z . However, it only actually declares the variable z . y and x are either invalid references to nonexistent variables (in strict mode ) or, worse, would implicitly create global variables for x and y in sloppy mode .

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Comparison operators
Operator Description Examples returning true
( ) Returns if the operands are equal.

( ) Returns if the operands are not equal.
( ) Returns if the operands are equal and of the same type. See also and .
( ) Returns if the operands are of the same type but not equal, or are of different type.
( ) Returns if the left operand is greater than the right operand.
( ) Returns if the left operand is greater than or equal to the right operand.
( ) Returns if the left operand is less than the right operand.
( ) Returns if the left operand is less than or equal to the right operand.

Note: => is not a comparison operator but rather is the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations ( + , - , * , / ), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to , if it is not already.

returns .

returns .

( ) Calculates the to the power, that is, returns .
returns .

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer: Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001 After: 1010 0000 0000 0000 0110 0000 0000 0001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Expression Result Binary Description

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value that -x - 1 evaluates to.

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of either type Number or BigInt : specifically, if the type of the left operand is BigInt , they return BigInt ; otherwise, they return Number .

The shift operators are listed in the following table.

Bitwise shift operators
Operator Description Example

( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Logical operators
Operator Usage Description
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) Returns if its single operand that can be converted to ; otherwise, returns .

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

Note that for the second case, in modern code you can use the Nullish coalescing operator ( ?? ) that works like || , but it only returns the second expression, when the first one is " nullish ", i.e. null or undefined . It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.

Most operators that can be used between numbers can be used between BigInt values as well.

One exception is unsigned right shift ( >>> ) , which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".

BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.

This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.

You can compare BigInts with numbers.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. It is regarded bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used instead.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object's property. The syntax is:

where object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property.

If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will yield undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

Since arrays are just objects, it's technically possible to delete elements from them. This is, however, regarded as a bad practice — try to avoid it. When you delete an array property, the array length is not affected and other elements are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the value undefined . To actually manipulate the array, use the various array methods such as splice .

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

Basic expressions

All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals , but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it to the form element, as in the following example:

Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python variables, varia b l e s.

Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Variables do not need to be declared with any particular type , and can even change type after they have been set.

If you want to specify the data type of a variable, this can be done with casting.

Advertisement

Get the Type

You can get the data type of a variable with the type() function.

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

Case-Sensitive

Variable names are case-sensitive.

This will create two variables:

Video: Python Variables

Python Tutorial on YouTube

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JavaScript Tutorial

JavaScript Basics

  • Introduction to JavaScript
  • JavaScript Versions
  • How to Add JavaScript in HTML Document?
  • JavaScript Statements
  • JavaScript Syntax
  • JavaScript Output
  • JavaScript Comments

JS Variables & Datatypes

Variables and datatypes in javascript.

  • Global and Local variables in JavaScript
  • JavaScript Let
  • JavaScript Const
  • JavaScript var

JS Operators

  • JavaScript Operators
  • Operator precedence in JavaScript
  • JavaScript Arithmetic Operators
  • JavaScript Assignment Operators
  • JavaScript Comparison Operators
  • JavaScript Logical Operators
  • JavaScript Bitwise Operators
  • JavaScript Ternary Operator
  • JavaScript Comma Operator
  • JavaScript Unary Operators
  • JavaScript Relational operators
  • JavaScript String Operators
  • JavaScript Loops
  • 7 Loops of JavaScript
  • JavaScript For Loop
  • JavaScript While Loop
  • JavaScript for-in Loop
  • JavaScript for...of Loop
  • JavaScript do...while Loop

JS Perfomance & Debugging

  • JavaScript | Performance
  • Debugging in JavaScript
  • JavaScript Errors Throw and Try to Catch
  • Objects in Javascript
  • Introduction to Object Oriented Programming in JavaScript
  • JavaScript Objects
  • Creating objects in JavaScript
  • JavaScript JSON Objects
  • JavaScript Object Reference

JS Function

  • Functions in JavaScript
  • How to write a function in JavaScript ?
  • JavaScript Function Call
  • Different ways of writing functions in JavaScript
  • Difference between Methods and Functions in JavaScript
  • Explain the Different Function States in JavaScript
  • JavaScript Function Complete Reference
  • JavaScript Arrays
  • JavaScript Array Methods
  • Best-Known JavaScript Array Methods
  • What are the Important Array Methods of JavaScript ?
  • JavaScript Array Reference
  • JavaScript Strings
  • JavaScript String Methods
  • JavaScript String Reference
  • JavaScript Numbers
  • How numbers are stored in JavaScript ?
  • How to create a Number object using JavaScript ?
  • JavaScript Number Reference
  • JavaScript Math Object
  • What is the use of Math object in JavaScript ?
  • JavaScript Math Reference
  • JavaScript Map
  • What is JavaScript Map and how to use it ?
  • JavaScript Map Reference
  • Sets in JavaScript
  • How are elements ordered in a Set in JavaScript ?
  • How to iterate over Set elements in JavaScript ?
  • How to sort a set in JavaScript ?
  • JavaScript Set Reference
  • JavaScript Date
  • JavaScript Promise
  • JavaScript BigInt
  • JavaScript Boolean
  • JavaScript Proxy/Handler
  • JavaScript WeakMap
  • JavaScript WeakSet
  • JavaScript Function Generator
  • JavaScript JSON
  • Arrow functions in JavaScript
  • JavaScript this Keyword
  • Strict mode in JavaScript
  • Introduction to ES6
  • JavaScript Hoisting
  • Async and Await in JavaScript

JavaScript Exercises

  • JavaScript Exercises, Practice Questions and Solutions

Variables and data types are foundational concepts in programming, serving as the building blocks for storing and manipulating information within a program. In JavaScript, understanding these concepts is essential for writing effective and efficient code.

In JavaScript, variables are used to store and manage data. They are created using the var, let, or const keyword.

var Keyword

The var keyword is used to declare a variable. It has a function-scoped or globally-scoped behavior.

Example:  In this example, we will declare variables using var.

let Keyword

The let keyword is a block-scoped variables. It’s commonly used for variables that may change their value.

Example:  In this example, we will declare variables using let.

const Keyword

The const keyword declares variables that cannot be reassigned. It’s block-scoped as well.

Example:  In this example, we will declare the variable using the const keyword.

JavaScript is a  dynamically typed  (also called loosely typed) scripting language. In JavaScript, variables can receive different data types over time. The latest ECMAScript standard defines eight data types Out of which seven data types are  Primitive (predefined)  and one  complex or Non-Primitive .

Primitive Data Types

The predefined data types provided by JavaScript language are known as primitive data types. Primitive data types are also known as in-built data types.

  • Number:  JavaScript numbers are always stored in double-precision 64-bit binary format IEEE 754. Unlike other programming languages, you don’t need int, float, etc to declare different numeric values.
  • String:  JavaScript Strings are similar to sentences. They are made up of a list of characters, which is essentially just an “array of characters, like “Hello GeeksforGeeks” etc.
  • Boolean:  Represent a logical entity and can have two values: true or false.
  • Null:  This type has only one value that is  null.
  • Undefined:  A variable that has not been assigned a value is  undefined.
  • Symbol:  Symbols return unique identifiers that can be used to add unique property keys to an object that won’t collide with keys of any other code that might add to the object.
  • BigInt:  BigInt is a built-in object in JavaScript that provides a way to represent whole numbers larger than 2^53-1.

Non-Primitive Data Types

The data types that are derived from primitive data types of the JavaScript language are known as non-primitive data types. It is also known as derived data types or reference data types.

  • Object:  It is the most important data type and forms the building blocks for modern JavaScript. We will learn about these data types in detail in further articles.

author

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Set data type for specific column when using read_csv from pandas

I have a large csv file (~10GB), with around 4000 columns. I know that most of data i will expect is int8, so i set:

Thing is, the final column (4000th position) is int32, is there away can i tell read_csv that use int8 by default, and at column 4000th, use int 32?

James's user avatar

  • 2 One hack I can think of: Read all the columns as int8. Then read only the 4000th column as int32 using usecols . Then replace it in the first dataframe. –  Thirupathi Thangavel Commented Jun 1, 2018 at 11:58

2 Answers 2

If you are certain of the number you could recreate the dictionary like this:

Considering that this works:

From the docs:

dtype : Type name or dict of column -> type, default None Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32} Use str or object to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.

Anton vBR's user avatar

Since you have no header, the column names are the integer order in which they occur, i.e. the first column is df[0] . To programmatically set the last column to be int32 , you can read the first line of the file to get the width of the dataframe, then construct a dictionary of the integer types you want to use with the number of the columns as the keys.

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python pandas or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Detecting a PL sphere and decompositions
  • When exactly are two functions said to be equal?
  • Rule of Thumb meaning in statistics
  • Ideal test/p-value calculation for difference in means with small sample size and right skewed data?
  • Was the phrase "white Christmas" indeed coined in the song?
  • Khmer Language is not properly displayed in layer fields in QGIS
  • Is my understanding of Quine's Bizet-Verdi counterfactuals correct?
  • Underfull \hbox with image
  • Find 10 float64s that give the least accurate sum
  • Why do trombones often play differently?
  • Door latch can be forced out of strike plate without turning handle
  • Is the work I do on the object always equal in magnitude but opposite in sign to the work the object does on me?
  • Are Context-Free languages closed under XOR?
  • Would you be able to look directly at the Sun if it were a red giant?
  • Was Jeremy Aster using male pronouns in reference to his cat, Patches, a blooper?
  • Is there a formulation of topology which excludes most of the pathological objects?
  • Help identifying planes from June 20 near Centennial airport in Colorado
  • What is the stronger emotion - to be annoyed or to be bothered?
  • Why is "Colourless green ideas sleep furiously" considered meaningless?
  • How to Ask a Top Professor to Co-Author a Paper with Me?
  • What can I add to my too-wet tuna+potato patties to make them less mushy?
  • Practical Combat Pipe
  • Can 3-speed 24/26" adult trike "keep up" with standard mountain/gravel bikes?

assignment data type

IMAGES

  1. Variables, Assignment & Data Types

    assignment data type

  2. Data type Assignment

    assignment data type

  3. Data Types, Data Structures and Abstract Data Types

    assignment data type

  4. What Are the Assignment Types and How to Cope With Each of Them

    assignment data type

  5. assignment.docx

    assignment data type

  6. What is Data Type and how many types of data type in PHP ?

    assignment data type

VIDEO

  1. ASSIGNMENT II DATA STRUCTURE AND ALGORITHM ANALYSIS

  2. Video Assignment

  3. How to build assignment data checks at the summary level of Variable Pay with the aggregate function

  4. BCA Second Semester Assignment! Data structure using C#Amityunviversity

  5. SERVICENOW Assignment Data Lookup Rules and Transfer maps @firstreview-xx5ms

  6. R Programming |Data Structure

COMMENTS

  1. How to Use Data Types in Python

    In Python, integers are known as int. They are a built-in data type for whole numbers. int can represent any size of integers without overflow errors because they can either be positive, zero, or negative. # Python Integer a = 7 y = -1 c = 0 print (a) # Output: 7 print (y) # Output: -1 print (c) # Output: 0.

  2. Python's Assignment Operator: Write Robust Assignments

    Assignment statements not only assign a value to a variable but also determine the data type of the variable at hand. This additional behavior is another important detail to consider in this kind of statement. Because Python is a dynamically typed language, successive assignments to a given variable can change the variable's data type ...

  3. Variables and Assignment

    The assignment operator, denoted by the "=" symbol, is the operator that is used to assign values to variables in Python. ... A data type is a classification of the type of information that is being stored in a variable. The basic data types that you will utilize throughout this book are boolean, int, float, string, list, tuple, dictionary ...

  4. Python Data Types (With Examples)

    Python Numeric Data type. In Python, numeric data type is used to hold numeric values. Integers, floating-point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex classes in Python.. int - holds signed integers of non-limited length.; float - holds floating decimal points and it's accurate up to 15 decimal places.

  5. Variables in Python

    Variable Assignment. Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. ... You now have a good understanding of some of Python's data types and know how to create variables that reference objects of those types ...

  6. Python Data Types

    Python has the following data types built-in by default, in these categories: Text Type: str: Numeric Types: int, float, complex: Sequence Types: list, tuple, range: Mapping Type: dict: Set Types: ... In Python, the data type is set when you assign a value to a variable: Example

  7. Data Types

    Data Types#. Evelyn Campbell, Ph.D. Python offers a number of different data types that can be manipulated and used by various functions. Some important built-in Python data types include booleans, strings, integers, and floats.These data types can be used to build various data structures, such as lists, dictionaries, arrays, and dataframes, which will be covered in Chapters 4 and 6.

  8. Variables and Assignment

    In Python, a single equals sign = is the "assignment operator." (A double equals sign == is the "real" equals sign.) Variables are names for values. In Python the = symbol assigns the value on the right to the name on the left. The variable is created when a value is assigned to it. Here, Python assigns an age to a variable age and a ...

  9. Python Data Types

    There are mainly four types of basic/primitive data types available in Python. Numeric: int, float, and complex. Sequence: String, list, and tuple. Set. Dictionary (dict) To check the data type of variable use the built-in function type() and isinstance(). The type() function returns the data type of the variable.

  10. Basic Data Types in Python: A Quick Exploration

    Python's numeric types, such as int, float, and complex. The str data type, which represents textual data in Python. The bytes and bytearray data types for storing bytes. Boolean values with Python's bool data type. With this knowledge, you're ready to start using all of the basic data types that are built into Python.

  11. How to declare variable type, C style in Python

    To clarify another statement you made, "you don't have to declare the data type" - it should be restated that you can't declare the data type. When you assign a value to a variable, the type of the value becomes the type of the variable. It's a subtle difference, but different nonetheless.

  12. Assignment and data types

    Assignment and data types. This exercise covers assigning values to variables and the basic data types in Python. Recall that unlike R, Python has only one way to assign values, by using the = sign. To assign the string hello to the variable x you would write: A quick refresher of the data types in Python: str (strings): usually to represent text.

  13. Python Data Types {Comprehensive Overview}

    Basic Data Types in Python. A data type is a characteristic that tells the compiler (or interpreter) how a programmer intends to use the data. There are two general categories of data types, differing whether the data is changeable after definition: 1. Immutable. Data types that are not changeable after assignment. 2.

  14. Variable Data Types Explained

    Basic Data Types. The most common basic data types available in most programming languages include: numbers: we use this for any data that is numeric or should be worked with as a number for addition or other math operations.. In some programming languages, there are multiple data types for numbers, depending on whether the number is an integer, decimal, or currency, for example.

  15. pandas.DataFrame.assign

    Assign new columns to a DataFrame. Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten. Parameters: **kwargsdict of {str: callable or Series} The column names are keywords. If the values are callable, they are computed on the DataFrame and assigned to the new columns.

  16. Data type

    The standard type hierarchy of Python 3. In computer science and computer programming, a data type (or simply type) is a collection or grouping of data values, usually specified by a set of possible values, a set of allowed operations on these values, and/or a representation of these values as machine types. A data type specification in a program constrains the possible values that an ...

  17. JavaScript Data Types

    The Concept of Data Types. In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer cannot safely solve this:

  18. Expressions and operators

    An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...

  19. Python Variables

    Python Variables Variable Names Assign Multiple Values Output Variables Global Variables Variable Exercises. ... If you want to specify the data type of a variable, this can be done with casting. Example. x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0.

  20. python

    you can set the types explicitly with pandas DataFrame.astype(dtype, copy=True, raise_on_error=True, **kwargs) and pass in a dictionary with the dtypes you want to dtype. here's an example: import pandas as pd. wheel_number = 5. car_name = 'jeep'. minutes_spent = 4.5. # set the columns. data_columns = ['wheel_number', 'car_name', 'minutes_spent ...

  21. Variables and Datatypes in JavaScript

    JavaScript is a dynamically typed (also called loosely typed) scripting language. In JavaScript, variables can receive different data types over time. The latest ECMAScript standard defines eight data types Out of which seven data types are Primitive (predefined) and one complex or Non-Primitive. Primitive Data Types.

  22. Developing an Integrated Activity-Based Travel Demand Model for

    The static assignment method includes an incremental assignment, a user equilibrium assignment, a stochastic assignment, and many other assignments. ... The required different built-in data inventories, such as the source type population, vehicle type vehicle miles traveled (VMT) distribution, road type distribution, and fuel supply data, are ...

  23. Introducing AWS Glue usage profiles for flexible cost control

    For Default worker type, choose G.1X. For Allowed worker types, choose G.1X, G.2X, G.4X, and G.8X. For Customize configurations for sessions, configure the same values. Choose Create usage profile. Next, create another usage profile for your business analysts, who need fewer workers and a lower timeout or idle timeout value. Choose Create usage ...

  24. Set data type for specific column when using read_csv from pandas

    2 int32. dtype: object. From the docs: dtype : Type name or dict of column -> type, default None. Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32} Use str or object to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.

  25. Introductory Medicinal Chemistry for Pharmacy Students: An Assignment

    New assessment approaches for medicinal chemistry in an introductory course within the pharmacy curriculum are presented. A required introductory pharmaceutical sciences course specific for first year entry-to-practice pharmacy (PharmD) students was developed concurrently within the mandated online learning environment of COVID19. Instead of in-person or online examinations for the medicinal ...