Rolex Pearlmaster Replica
  Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
This article is part of in the series
Published: Wednesday 9th May 2012
Last Updated: Wednesday 29th December 2021

Overview of Python Lists and Tuples

Two of the most commonly used built-in data types in Python are the list and the tuple.

Lists and tuples are part of the group of sequence data types—in other words, lists and tuples store one or more objects or values in a specific order. The objects stored in a list or tuple can be of any type, including the nothing type defined by the None keyword.

The big difference between lists and tuples is that lists are mutable, however tuples are immutable. Meaning once tuples are created, objects can't be added or removed, and the order cannot be changed. However, certain objects in tuples can be changed, as we'll see later.

Creating a Python List or Tuple

Creating a list or tuple is easy, here are some empty ones:

[python]
# Lists must be surrounded by brackets
>>> emptylst = []
# Tuples may or may not be surrounded by parenthesis
>>> emptytup = ()
[/python]

To create non-empty lists or tuples, values are separated by commas:

[python]
# Lists must be surrounded by brackets
>>> lst = [1, 2, 3]
>>> lst
[1, 2, 3]
# Tuples may or may not be surrounded by parenthesis
>>> tup = 1, 2, 3
>>> tup
(1, 2, 3)
>>> tup = ('one', 'two', 'three')
>>> tup
('one', 'two', 'three')
[/python]

Note: To create a tuple with only one value, add a trailing comma to the value.

[python]
# The length of this tuple is 1
>>> tup2 = 0,
>>> tup2
(0,)
[/python]

Get Python List or Tuple Values

The values in lists and tuples, as with other sequence types, are referenced by an index. This is a number, referring to the sequence of the value, that begins with 0 for the first value. Such as the following:

[python]
>>> lst[0]
1
>>> tup[1]
'two'
[/python]

Using an index below zero gets the values starting from the end of the list or tuple:

[python]
>>> lst[-1]
3
>>> tup[-2]
'two'
[/python]

Slicing Python Lists and Tuples

Multiple values can be referenced by "slicing" the list or tuple (referencing a range[start:stop]):

[python]
>>> lst[0:2]
[1, 2]
# Note an out-of-range stopindex translates to the end
>>> tup[1:5]
('two', 'three')
[/python]

Assigning a Python List Value by Index

Values for lists can be assigned with indexes (as long as the index already exists), but not for tuples:

[python]
>>> lst[2] = 'three'
>>> lst
[1, 2, 'three']
>>> tup[2] = 3
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
tup[2] = 3
TypeError: 'tuple' object does not support item assignment
[/python]

Adding to a Python List

Values can also be added to lists (and lists can be combined, or concatenated) with the '+' operator, or with the standard append method:

[python]
# concatenation, the same as lst = lst + [None]
>>> lst += [None]
>>> lst
[1, 2, 'three', None]
>>> lst.append(5)
>>> lst
[1, 2, 'three', None, 5]
[/python]

The Python del Keyword for Lists

Values can be removed from lists with the del keyword:

[python]
>>> del lst[3]
>>> lst
[1, 2, 'three', 5]
# Slicing deletion; no stop index means through the end
>>> del lst[2:]
>>> lst
[1, 2]
[/python]

Assignment and deletion methods for lists don't work for tuples, but concatenation works:

[python]
# Note only tuples can be added to tuples
>>> tup += (4,)
>>> tup
('one', 'two', 'three', 4)
[/python]

Even though tuples are not mutable like lists, with the slicing technique and a little creativity, tuples can be manipulated like lists:

[python]
# Almost like slice deletion
>>> tup = tup[0:2]
>>> tup
('one', 'two')
>>> tup2 += tup
>>> tup2
# almost like index assignment
>>> tup2 = tup2[0:1] + (1,) + tup2[2:]
>>> tup2
(0, 1, 'two')
[/python]

In addition, if a tuple contains a list, the mutability of the list in that tuple is preserved:

[python]
>>> tup3 = 0, 'one', None, []
>>> tup3[3].append('three')
>>> tup3
(0, 'one', None, ['three'])
[/python]

Aside from the methods described here more exist for lists and tuples, but these cover the most common list and tuple operations. And remember, lists and tuples can be nested (can contain lists and tuples, and other data types that store sets of values, such as dictionaries), and can store different types simultaneously, making them very useful.

About The Author

Les De Shay

Latest Articles


Tags

  • deque
  • heap
  • Data Structure
  • howto
  • dict
  • csv in python
  • logging in python
  • Python Counter
  • python subprocess
  • numpy module
  • Python code generators
  • KMS
  • Office
  • modules
  • web scraping
  • scalable
  • pipx
  • templates
  • python not
  • pytesseract
  • env
  • push
  • search
  • Node
  • python tutorial
  • dictionary
  • csv file python
  • python logging
  • Counter class
  • Python assert
  • linspace
  • numbers_list
  • Tool
  • Key
  • automation
  • website data
  • autoscale
  • packages
  • snusbase
  • boolean
  • ocr
  • pyside6
  • pop
  • binary search
  • Insert Node
  • Python tips
  • python dictionary
  • Python's Built-in CSV Library
  • logging APIs
  • Constructing Counters
  • Assertions
  • Matplotlib Plotting
  • any() Function
  • Activation
  • Patch
  • threading
  • scrapy
  • game analysis
  • dependencies
  • security
  • not operation
  • pdf
  • build gui
  • dequeue
  • linear search
  • Add Node
  • Python tools
  • function
  • python update
  • logging module
  • Concatenate Data Frames
  • python comments
  • matplotlib
  • Recursion Limit
  • License
  • Pirated
  • square root
  • website extract python
  • steamspy
  • processing
  • cybersecurity
  • variable
  • image processing
  • incrementing
  • Data structures
  • algorithm
  • Print Node
  • installation
  • python function
  • pandas installation
  • Zen of Python
  • concatenation
  • Echo Client
  • Pygame
  • NumPy Pad()
  • Unlock
  • Bypass
  • pytorch
  • zipp
  • steam
  • multiprocessing
  • type hinting
  • global
  • argh
  • c vs python
  • Python
  • stacks
  • Sort
  • algorithms
  • install python
  • Scopes
  • how to install pandas
  • Philosophy of Programming
  • concat() function
  • Socket State
  • % Operator
  • Python YAML
  • Crack
  • Reddit
  • lightning
  • zip files
  • python reduce
  • library
  • dynamic
  • local
  • command line
  • define function
  • Pickle
  • enqueue
  • ascending
  • remove a node
  • Django
  • function scope
  • Tuple in Python
  • pandas groupby
  • pyenv
  • socket programming
  • Python Modulo
  • Dictionary Update()
  • Hack
  • sdk
  • python automation
  • main
  • reduce
  • typing
  • ord
  • print
  • network
  • matplotlib inline
  • Pickling
  • datastructure
  • bubble sort
  • find a node
  • Flask
  • calling function
  • tuple
  • GroupBy method
  • Pythonbrew
  • Np.Arange()
  • Modulo Operator
  • Python Or Operator
  • Keygen
  • cloud
  • pyautogui
  • python main
  • reduce function
  • type hints
  • python ord
  • format
  • python socket
  • jupyter
  • Unpickling
  • array
  • sorting
  • reversal
  • Python salaries
  • list sort
  • Pip
  • .groupby()
  • pyenv global
  • NumPy arrays
  • Modulo
  • OpenCV
  • Torrent
  • data
  • int function
  • file conversion
  • calculus
  • python typing
  • encryption
  • strings
  • big o calculator
  • gamin
  • HTML
  • list
  • insertion sort
  • in place reversal
  • learn python
  • String
  • python packages
  • FastAPI
  • argparse
  • zeros() function
  • AWS Lambda
  • Scikit Learn
  • Free
  • classes
  • turtle
  • convert file
  • abs()
  • python do while
  • set operations
  • data visualization
  • efficient coding
  • data analysis
  • HTML Parser
  • circular queue
  • effiiciency
  • Learning
  • windows
  • reverse
  • Python IDE
  • python maps
  • dataframes
  • Num Py Zeros
  • Python Lists
  • Fprintf
  • Version
  • immutable
  • python turtle
  • pandoc
  • semantic kernel
  • do while
  • set
  • tabulate
  • optimize code
  • object oriented
  • HTML Extraction
  • head
  • selection sort
  • Programming
  • install python on windows
  • reverse string
  • python Code Editors
  • Pytest
  • pandas.reset_index
  • NumPy
  • Infinite Numbers in Python
  • Python Readlines()
  • Trial
  • youtube
  • interactive
  • deep
  • kernel
  • while loop
  • union
  • tutorials
  • audio
  • github
  • Parsing
  • tail
  • merge sort
  • Programming language
  • remove python
  • concatenate string
  • Code Editors
  • unittest
  • reset_index()
  • Train Test Split
  • Local Testing Server
  • Python Input
  • Studio
  • excel
  • sgd
  • deeplearning
  • pandas
  • class python
  • intersection
  • logic
  • pydub
  • git
  • Scrapping
  • priority queue
  • quick sort
  • web development
  • uninstall python
  • python string
  • code interface
  • PyUnit
  • round numbers
  • train_test_split()
  • Flask module
  • Software
  • FL
  • llm
  • data science
  • testing
  • pathlib
  • oop
  • gui
  • visualization
  • audio edit
  • requests
  • stack
  • min heap
  • Linked List
  • machine learning
  • scripts
  • compare string
  • time delay
  • PythonZip
  • pandas dataframes
  • arange() method
  • SQLAlchemy
  • Activator
  • Music
  • AI
  • ML
  • import
  • file
  • jinja
  • pysimplegui
  • notebook
  • decouple
  • queue
  • heapify
  • Singly Linked List
  • intro
  • python scripts
  • learning python
  • python bugs
  • ZipFunction
  • plus equals
  • np.linspace
  • SQLAlchemy advance
  • Download
  • No
  • nlp
  • machiine learning
  • dask
  • file management
  • jinja2
  • ui
  • tdqm
  • configuration
  • Python is a beautiful language.