YouTip LogoYouTip

Python Variable Types

Python2.x Python Variable Types

Variables store values in memory, which means that creating a variable allocates space in memory.

Based on the variable's data type, the interpreter allocates the appropriate amount of memory and determines what kind of data can be stored.

Therefore, variables can be assigned different data types, allowing them to store integers, decimals, or characters.


Variable Assignment

Variable assignment in Python does not require type declaration.

Each variable created in memory includes information such as its identity, name, and data.

Every variable must be assigned a value before use; the variable is only created after assignment.

The equals sign = is used to assign values to variables.

The left side of the = operator is the variable name, and the right side is the value stored in the variable. For example:

Example (Python 2.0+)

counter = 100
miles = 1000.0
name = "John"
print counter
print miles
print name

Run Example Β»

In the above example, the values 100, 1000.0, and "John" are assigned to the variables counter, miles, and name, respectively.

Executing the above program produces the following output:

100
1000.0
John

Multiple Variable Assignment

Python allows you to assign values to multiple variables simultaneously. For example:

a = b = c = 1

In this example, an integer object with the value 1 is created, and all three variables refer to the same memory location.

You can also assign multiple values to multiple variables. For example:

a, b, c = 1, 2, "john"

In this case, the integer objects 1 and 2 are assigned to variables a and b, respectively, and the string object "john" is assigned to variable c.


Standard Data Types

Data stored in memory can be of various types.

For instance, a person's age can be stored as a number, while their name can be stored as characters.

Python defines several standard types for storing different kinds of data.

Python has five standard data types:

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Numeric data types are used to store numerical values.

They are immutable, meaning that modifying a numeric value creates a new object.

When you assign a value, a Number object is created:

var1 = 1
var2 = 10

You can also delete references to objects using the del statement.

The syntax for the del statement is:

del var1[,var2[,var3[....,varN]]]

You can delete references to one or more objects using the del statement. For example:

del var
del var_a, var_b

Python supports four distinct numeric types:

  • int (signed integer)
  • long (long integer, also representing octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

Examples

Examples of numeric types:

int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3e+18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2E-12 4.53e-7j
  • Long integers can also be written with a lowercase l, but it's recommended to use uppercase L to avoid confusion with the digit 1. Python displays long integers using L.
  • Python also supports complex numbers, which consist of a real and an imaginary part. They can be represented as a + bj or using complex(a, b). Both the real part a and imaginary part b are floating-point numbers.

Note: The long type exists only in Python 2.X. Starting from version 2.2, when an int overflows, it automatically becomes a long. In Python 3.X, the long type has been removed and replaced entirely by int.


Python Strings

A string is a sequence of characters composed of digits, letters, and underscores.

It is generally denoted as:

s = "a1a2Β·Β·Β·an"  # n>=0

It is the data type used in programming languages to represent text.

Python strings support two indexing orders:

  • Left-to-right indexing starts at 0 by default, with the maximum index being the string length minus 1.
  • Right-to-left indexing starts at -1 by default, with the maximum range reaching the beginning of the string.

Image 1

To extract a substring from a string, you can use [start:end] slicing. Indexing starts at 0 and can be positive or negative. Omitting an index means going to the beginning or end.

The substring obtained via [start:end] includes the character at the start index but excludes the character at the end index.

For example:

>>> s = 'abcdef'
>>> s[1:5]
'bcde'

When using colon-separated slicing, Python returns a new object containing the continuous elements between the specified offsets, including the lower bound.

The result above includes s (value 'b') but excludes the end index s (value 'f').

Image 2

The plus sign (+) is the string concatenation operator, and the asterisk (*) is the repetition operator. See the following example:

Example (Python 2.0+)

str = 'Hello World!'
print str
print str
print str[2:5]
print str[2:]
print str * 2
print str + "TEST"

The output of the above example is:

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Lists

List is the most frequently used data type in Python.

Lists can implement most collection-like data structures. They can contain characters, numbers, strings, and even other lists (nested lists).

Lists are denoted by square brackets [] and are Python's most versatile compound data type.

List slicing also uses [start:end] notation to extract sublists. Left-to-right indexing starts at 0 by default, and right-to-left indexing starts at -1. Omitting an index means going to the beginning or end.

Image 3

The plus sign (+) is the list concatenation operator, and the asterisk (*) is the repetition operator. See the following example:

Example (Python 2.0+)

list = ['', 786 , 2.23, 'john', 70.2]
tinylist = [123, 'john']
print list
print list
print list[1:3]
print list[2:]
print tinylist * 2
print list + tinylist

The output of the above example is:

['', 786, 2.23, 'john', 70.2]

[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['', 786, 2.23, 'john', 70.2, 123, 'john']

Python list slicing can accept a third parameter, which specifies the step size. The following example slices from index 1 to index 4 with a step size of 2 (skipping one element):

Image 4


Python Tuples

Tuples are another data type similar to Lists.

Tuples are denoted by parentheses (), with elements separated by commas. However, tuples cannot be reassigned after creationβ€”they are essentially read-only lists.

Example (Python 2.0+)

tuple = ('', 786 , 2.23, 'john', 70.2)
tinytuple = (123, 'john')
print tuple
print tuple
print tuple[1:3]
print tuple[2:]
print tinytuple * 2
print tuple + tinytuple

The output of the above example is:

('', 786, 2.23, 'john', 70.2)

(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('', 786, 2.23, 'john', 70.2, 123, 'john')

The following operation on a tuple is invalid because tuples do not allow updates, whereas lists do:

Example (Python 2.0+)

tuple = ('', 786 , 2.23, 'john', 70.2)
list = ['', 786 , 2.23, 'john', 70.2]
tuple = 1000    # Invalid for tuples
list = 1000     # Valid for lists

Since tuples are immutable, executing the above code results in an error:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    tuple = 1000    # Invalid operation on tuple
TypeError: 'tuple' object does not support item assignment

Python Dictionaries

Dictionaries are Python's most flexible built-in data structure type besides lists. Lists are ordered collections of objects, while dictionaries are unordered collections.

The key difference is that dictionary elements are accessed by keys rather than by offset.

Dictionaries are denoted by curly braces {} and consist of key-value pairs.

Example (Python 2.0+)

dict = {}
dict['one'] = "This is one"
dict = "This is two"
tinydict = {'name': '','code':6734, 'dept': 'sales'}

print dict['one']
print dict
print tinydict
print tinydict.keys()
print tinydict.values()

The output is:

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': ''}
['dept', 'code', 'name']
['sales', 6734, '']

Python Data Type Conversion

Sometimes, we need to convert between built-in data types. To perform type conversion, simply use the desired type as a function name.

The following built-in functions can convert between data types. These functions return a new object representing the converted value.

Function Description
int(x [,base]) Converts x to an integer
long(x [,base] ) Converts x to a long integer
float(x) Converts x to a floating-point number
complex(real [,imag]) Creates a complex number
str(x) Converts object x to a string
repr(x) Converts object x to an expression string
eval(str) Evaluates a valid Python expression in a string and returns an object
tuple(s) Converts sequence s to a tuple
list(s) Converts sequence s to a list
set(s) Converts sequence s to a set
← Python While LoopPython Basic Syntax β†’