Basic Python Lists, Tuples, Sets
   4 min read


Common functions and methods for lists, tuples, and sets.

Lists

listName = [item1, item2, item3…]

Lists may contain multiple data types (strings, integers, etc.)
Items in a list are indexed in numerical order from 0.
Lists permit duplicate values.
Lists are mutable. Items can be changed, added, reordered, or removed.

Example:

list1 = ["Ali", 17639, True] #list contains string, integer, and Boolean items.
print(list1)

['Ali', 17639, True]

Tuples

tupleName = (item1,)
tupleName = (item1, item2, item3…)

A tuple may contain one or more items (for a tuple of one item, the comma is mandatory).
Tuples may contain multiple data types (strings, integers, etc.)
Items in a tuple are indexed in numerical order from 0.
Tuples permit duplicate values.
Tuples are immutable. Items in a tuple cannot be changed or removed, and new items cannot be added.

Example:

tuple1 = ("Ali", 17639, True) #tuple contains string, integer, and Boolean items.
print(tuple1)

['Ali', 17639, True]

Determine Length of List or Tuple

len()

Begins with 1.

Example:

>>> len(list1)

3

Access Items

Access items in a list or a tuple by referencing the index in square brackets.
Access the last item using -1.
To access a range, give the start or end index, or specify both. If the end index is specified, the result includes items upto (but excluding) the final index.

Example:

colorList = ["red", "blue", "green", "yellow", "cyan", "magenta"]
print(colorList[-1])

magenta

Example:

colorList = ["red", "blue", "green", "yellow", "cyan", "magenta"]
print(colorList[3:]) #omit the end index (no space after colon).

['yellow', 'cyan', 'magenta']

Example:

colorList = ["red", "blue", "green", "yellow", "cyan", "magenta"]
print(colorList[:3]) #omit the first index (no space before colon).

['red', 'blue', 'green'] #returns a list upto but excluding the specified end index.

Example:

colorList = ["red", "blue", "green", "yellow", "cyan", "magenta"]
print(colorList[2:4])

['green', 'yellow'] #returns a list from the first specified index upto but excluding the specified end index.

Generate a list of integers

range()

Example:

print(list(range(10)))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #generates a list of integers from 0 to 9.

Join or Multiply

+
*
Use operators to join or multiply lists or tuples.

Example:

primaryColors = ["red", "blue", "green"]
secondaryColors = ["yellow", "cyan", "magenta"]
colorList = primaryColors + secondaryColors
print(colorList)

['red', 'blue', 'green', 'yellow', 'cyan', 'magenta']

Example:

cars = ("Toyota", "Skoda") #tuple
carsRented = cars * 2
print(carsRented)

('Toyota', 'Skoda', 'Toyota', 'Skoda')

Sets

setName = {item1, item2, item3…}

Sets may contain multiple data types (strings, integers, etc.)
Items in a set are not indexed and unordered.
Sets do not permit duplicate values (duplicate values are disregarded). Use case: convert a list to a set to deduplicate items.
Items in a set cannot be changed or removed, but new items can be added.

Add item to an existing set

set.add(item)
Add new item to existing set

set.update(set2)
Update an existing set with items from another set

Example:

ingredients = {"flour", "butter", "sugar"}
print(ingredients)
ingredients.add("salt")
print(ingredients)

{'flour', 'sugar', 'butter'} #items unordered.
{'flour', 'sugar', 'salt', 'butter'}

Example:

cars = {"Toyota", "Skoda"}
newCars = {"Fiat", "Toyota", "Honda"}
cars.update(newCars)
print(cars)

{'Fiat', 'Toyota', 'Honda', 'Skoda'} #duplicate items omitted.

List methods

Resources: See W3 Schools Tutorials for further examples.

MethodSyntaxNotes
Split stringstring.split()Accepts a separator as an input parameter. If no separator is specified (default), the string is split at whitespaces (blanks, newlines, tabs) and the split string is returned as a list. If a separator is specified, the string is split at the separator, the separator is omitted from the string, and the remaining parts returned in a list.
Join stringseparator.join(iterable)Accepts an iterable (list etc.) as an input parameter, and uses the specified separator to join items in a string.
Append itemlistName.append('new_item')Append a new item to the end of a list.
Insert itemlistName.insert(index, 'new_item')Insert a new item at the specfied index in a list.
Change itemlistName[index] = 'new_value'Change the value of an item at a specfied index in a list. To change a range of values, specify the start and end index of the range [start index:end index]. Values change upto but not including the end index.
Remove itemlistName.remove('item')Remove a specified item from a list.
Remove last/indexed itemlistName.remove()Specify the index of the item to be removed as a parameter. If no parameter is specified (default), the last item in the list is removed.
Extend listlist1.extend(list2)Extend list1 by adding items from list2. Also use for tuples, sets, dictionaries etc.
Delete listdel listNameDelete a list. Can also delete a specified item using square brackets to specify the index.
Sort listlistName.sort()Sort a list in ascending order. To sort in descending order use (reverse = True) as the input parameter.
Copy listnewList = existingList.copy()Create a copy of an existing list.