0% found this document useful (0 votes)
7 views7 pages

Python Lists, Tuples, and Dictionaries Guide

Uploaded by

fortiratra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Python Lists, Tuples, and Dictionaries Guide

Uploaded by

fortiratra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

int_list = [1, 2, 3]

string_list = ['abc', 'defghi']

A list can be empty:

empty_list = []

The elements of a list are not restricted to a single data type, which makes sense given that Python is
a dynamic

language:

mixed_list = [1, 'abc', True, 2.34, None]

A list can contain another list as its element:

nested_list = [['a', 'b', 'c'], [1, 2, 3]]

The elements of a list can be accessed via an index, or numeric representation of their position. Lists
in Python are

zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1
and so on:

names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric']

print(names[0]) # Alice

print(names[2]) # Craig

Indices can also be negative which means counting from the end of the list (-1 being the index of the
last element).

So, using the list from the above example:

print(names[-1]) # Eric

print(names[-4]) # Bob

Lists are mutable, so you can change the values in a list:

names[0] = 'Ann'

print(names)

# Outputs ['Ann', 'Bob', 'Craig', 'Diana', 'Eric']

Besides, it is possible to add and/or remove elements from a list:

Append object to end of list with [Link](object), returns None.

names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric']

[Link]("Sia")

print(names)

# Outputs ['Alice', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia']


Add a new element to list at a specific index. [Link](index, object)

[Link](1, "Nikki")

print(names)

# Outputs ['Alice', 'Nikki', 'Bob', 'Craig', 'Diana', 'Eric', 'Sia']

Remove the first occurrence of a value with [Link](value), returns None

[Link]("Bob")

print(names) # Outputs ['Alice', 'Nikki', 'Craig', 'Diana', 'Eric', 'Sia']

[Link] – Python® Notes for Professionals 17

Get the index in the list of the first item whose value is x. It will show an error if there is no such
item.

[Link]("Alice")

Count length of list

len(names)

count occurrence of any item in list

a = [1, 1, 1, 2, 3, 4]

[Link](1)

Reverse the list

[Link]()

[4, 3, 2, 1, 1, 1]

# or

a[::-1]

[4, 3, 2, 1, 1, 1]

Remove and return item at index (defaults to the last item) with [Link]([index]), returns the item

[Link]() # Outputs 'Sia'

You can iterate over the list elements like below:

for element in my_list:

print (element)

Tuples
A tuple is similar to a list except that it is fixed-length and immutable. So the values in the tuple
cannot be changed

nor the values be added to or removed from the tuple. Tuples are commonly used for small
collections of values

that will not need to change, such as an IP address and port. Tuples are represented with
parentheses instead of

square brackets:

ip_address = ('[Link]', 8080)

The same indexing rules for lists also apply to tuples. Tuples can also be nested and the values can be
any valid

Python valid.

A tuple with only one member must be defined (note the comma) this way:

one_member_tuple = ('Only member',)

or

one_member_tuple = 'Only member', # No brackets

or just using tuple syntax

[Link] – Python® Notes for Professionals 18

one_member_tuple = tuple(['Only member'])

Dictionaries

A dictionary in Python is a collection of key-value pairs. The dictionary is surrounded by curly braces.
Each pair is

separated by a comma and the key and value are separated by a colon. Here is an example:

state_capitals = {

'Arkansas': 'Little Rock',

'Colorado': 'Denver',

'California': 'Sacramento',

'Georgia': 'Atlanta'

To get a value, refer to it by its key:

ca_capital = state_capitals['California']

You can also get all of the keys in a dictionary and then iterate over them:

for k in state_capitals.keys():

print('{} is the capital of {}'.format(state_capitals[k], k))


Dictionaries strongly resemble JSON syntax. The native json module in the Python standard library
can be used to

convert between JSON and dictionaries.

set

A set is a collection of elements with no repeats and without insertion order but sorted order. They
are used in

situations where it is only important that some things are grouped together, and not what order they
were

included. For large groups of data, it is much faster to check whether or not an element is in a set
than it is to do

the same for a list.

Defining a set is very similar to defining a dictionary:

first_names = {'Adam', 'Beth', 'Charlie'}

Or you can build a set using an existing list:

my_list = [1,2,3]

my_set = set(my_list)

Check membership of the set using in:

if name in first_names:

print(name)

You can iterate over a set exactly like a list, but remember: the values will be in an arbitrary,
implementationdefined

order.

defaultdict

A defaultdict is a dictionary with a default value for keys, so that keys for which no value has been
explicitly

defined can be accessed without errors. defaultdict is especially useful when the values in the
dictionary are

collections (lists, dicts, etc) in the sense that it does not need to be initialized every time when a new
key is used.

[Link] – Python® Notes for Professionals 19

A defaultdict will never raise a KeyError. Any key that does not exist gets the default value returned.

For example, consider the following dictionary

>>> state_capitals = {

'Arkansas': 'Little Rock',


'Colorado': 'Denver',

'California': 'Sacramento',

'Georgia': 'Atlanta'

If we try to access a non-existent key, python returns us an error as follows

>>> state_capitals['Alabama']

Traceback (most recent call last):

File "<ipython-input-61-236329695e6f>", line 1, in <module>

state_capitals['Alabama']

KeyError: 'Alabama'

Let us try with a defaultdict. It can be found in the collections module.

>>> from collections import defaultdict

>>> state_capitals = defaultdict(lambda: 'Boston')

What we did here is to set a default value (Boston) in case the give key does not exist. Now populate
the dict as

before:

>>> state_capitals['Arkansas'] = 'Little Rock'

>>> state_capitals['California'] = 'Sacramento'

>>> state_capitals['Colorado'] = 'Denver'

>>> state_capitals['Georgia'] = 'Atlanta'

If we try to access the dict with a non-existent key, python will return us the default value i.e. Boston

>>> state_capitals['Alabama']

'Boston'

and returns the created values for existing key just like a normal dictionary

>>> state_capitals['Arkansas']

'Little Rock'

Section 1.6: IDLE - Python GUI

IDLE is Python’s Integrated Development and Learning Environment and is an alternative to the
command line. As

the name may imply, IDLE is very useful for developing new code or learning python. On Windows
this comes with
the Python interpreter, but in other operating systems you may need to install it through your
package manager.

The main purposes of IDLE are:

Multi-window text editor with syntax highlighting, autocompletion, and smart indent

Python shell with syntax highlighting

Integrated debugger with stepping, persistent breakpoints, and call stack visibility

Automatic indentation (useful for beginners learning about Python's indentation)

[Link] – Python® Notes for Professionals 20

Saving the Python program as .py files and run them and edit them later at any them using IDLE.

In IDLE, hit F5 or run Python Shell to launch an interpreter. Using IDLE can be a better learning
experience for

new users because code is interpreted as the user writes.

Note that there are lots of alternatives, see for example this discussion or this list.

Troubleshooting

Windows

If you're on Windows, the default command is python. If you receive a "'python' is not recognized"
error,

the most likely cause is that Python's location is not in your system's PATH environment variable. This
can be

accessed by right-clicking on 'My Computer' and selecting 'Properties' or by navigating to 'System'


through

'Control Panel'. Click on 'Advanced system settings' and then 'Environment Variables...'. Edit the PATH
variable

to include the directory of your Python installation, as well as the Script folder (usually

C:\Python27;C:\Python27\Scripts). This requires administrative privileges and may require a restart.

When using multiple versions of Python on the same machine, a possible solution is to rename one
of the

[Link] files. For example, naming one version [Link] would cause python27 to become
the

Python command for that version.

You can also use the Python Launcher for Windows, which is available through the installer and
comes by

default. It allows you to select the version of Python to run by using py -[x.y] instead of python[x.y].
You
can use the latest version of Python 2 by running scripts with py -2 and the latest version of Python 3
by

running scripts with py -3.

Debian/Ubuntu/MacOS

This section assumes that the location of the python executable has been added to the PATH
environment

variable.

If you're on Debian/Ubuntu/MacOS, open the terminal and type python for Python 2.x or python3
for Python

3.x.

Type which python to see which Python interpreter will be used.

Arch Linux

The default Python on Arch Linux (and descendants) is Python 3, so use python or python3 for
Python 3.x and

python2 for Python 2.x.

Other systems

Python 3 is sometimes bound to python instead of python3. To use Python 2 on these systems where
it is

installed, you can use python2.

You might also like