Python slice list of tuples

Ultimate Guide to Lists, Tuples, Arrays and Dictionaries For Beginners.

A simple guide to creating, updating and manipulating pythons most popular data structures, and their key differences.

Susan Maina

Dec 7, 2020·6 min read

Photo by Priscilla Du Preez on Unsplash

Python uses data structures to store and organize other objects. The most commonly used data structures are lists and dictionaries. In this article we also talk about tuples and arrays. Tuples have a slight performance improvement to lists and can be used as indices to dictionaries. Arrays only store values of similar data types and are better at processing many values quickly. Another common data structure is a Set which only stores unique values and is therefore useful for removing duplicates from lists.

Lists

These are mutable sequences of objects enclosed by square brackets [].

Mutable means that you can manipulate the list by adding to it, removing elements, updating already existing elements, etc. Sequence means that the elements are ordered, and indexed to start at index 0. The objects may be any object type in python, from other lists to functions to custom objects. Square brackets enclose the list values .

Creating a list using list=[values]

list_1 = ['head', 'ears', 3, 'legs', 5.8]

Adding elements to a list we use list.append[a]

list_1.append['hair']
print[list_1]
### Results
['head', 'ears', 3, 'legs', 5.8, 'hair']

Removing/deleting elements from a list using list.remove[a]

list_1.remove['head']
list_1
### Results
['ears', 3, 'legs', 5.8, 'hair']

Updating list elements using list[index]=new_value

list_2 = ['beef', 'chicken', 'pork']
list_2[2] = 'mutton'
print[list_2]
### Results
['beef', 'chicken', 'mutton']

Retrieving elements from a list using list[index]

list_1 = ['ears', 3, 'legs', 5.8, 'hair']print[list_1[0]] #first element
print[list_1[:]] #all the elements
print[list_1[2:4]] # from 3rd element to but not including 5th
print[list_1[-1]] #last element
print[list_1[1:-1]] #2nd element to but not including last
### Results
ears
['ears', 3, 'legs', 5.8, 'hair']
['legs', 5.8]
hair
[3, 'legs', 5.8]

Adding lists together using list+list

list_1 + list_2### Results
['ears', 3, 'legs', 5.8, 'hair', 'beef', 'chicken', 'mutton']

Repeating a list many times using list*number

a = [1,2,3]
print[a * 3]
### Results
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Checking if a value is a member of a list using value in list

print['beef' in list_2]### Results
True

Check the number of elements/ length of a list using len[list]

print[len[list_1]]### Results
5

Getting the minimum and maximum values of a list using max[list] and min[list]. Note that a TypeError will be thrown if the list has mixed objects such as Int and Strings.

a = [1,2,3]
b = [a, ba, ca, za, ze]
print[min[a]]
print[max[b]]
### Result
1
ze

Tuples

These are immutable sequences of objects enclosed by parentheses [] normal brackets.

Immutable means that once a tuple is created, you cannot manipulate its contents, for example removing, updating or adding elements. Similar to lists above, the elements are in an ordered and indexed Sequence and can contain any python Objects. However, the tuple is created using parentheses, which are just normal brackets[].

Tuples and Lists enjoy a lot of similar operations. For example you can create a tuple from elements of only one object type, or mixed types. Create a tuple using tuple = [values]

tuple_1 = [3, 'bags', 'belt', 2020, 7.9]
tuple_2 = [1,4,6,2]

You can also retrieve tuple elements by index, slice the tuple to retrieve a subset of the values, get the length of the tuple, as well as the maximum and minimum values just like we did with lists above.

print[tuple_1[0]]
print[tuple_1[2:-1]]
print['backpack' in tuple_1]
print[len[tuple_1]]
print[max[tuple_2]]
### Results
3
['belt', 2020]
False
5
6

Side tip: Unpacking lists and tuples.

This is a cool and convenient way to re-assign elements of lists and tuples into individual variables. This is by assigning the list to variables as in var_a,var_b=list. Note that if you try to unpack to less or more variables than the elements in the list, a ValueError is thrown.

t_1 = [1,2,3,4,5]
a,b,c,d,e = t_1
print[c]
### Results
3

Arrays

Python has a separate module for handling arrays called array. Unlike lists, Tuples, Sets and Dictionaries which are inbuilt into the python library, you have to import the array module before using it in your code.

An array is a mutable sequence of similar type objects stored at contiguous/adjacent memory locations.

Mutable means that you can manipulate an array by adding or removing elements, updating already existing elements, etc. Sequence means that the elements are ordered, and indexed to start at index 0. However, unlike lists, arrays can only contains items of the same data type such as Ints, Floats, or Characters.

To initialize an array, you call the array method of the array module and pass the data type code, and the items enclosed in square brackets. For example array_name = array.array[type code,[array items]]. The type code is a single character like i, f or u representing Integers, Floats or Unicode Characters respectively. Check out this documentation for a table of all type codes.

import array as arrarr_ints = arr.array['i', [1,2,3]]
arr_floats = arr.array['f', [2.5, 5.5, 3.0]]
arr_chars = arr.array['u', ['a','b','c']]

Retrieve the value at a certain index from an array using Array[index]. You can also get the location[index] of a value using Array.index[value].

arr_floats = arr.array['f', [2.5, 5.5, 3.0]]
print[arr_floats[1]]
print[arr_floats.index[3.0]]
### Results
5.5
2

Inserting elements from an array use Array.insert[index,value]. The index is the intended location of the new value. Note that the two arguments must be provided to the insert method or a TypeError will be thrown. You can also use Array.append[value] to add a value at the end position.

arr_chars = arr.array['u', ['a','b','c']]
arr_chars.insert[2, 'g']
print[arr_chars]
### Results
array['u', 'abgc']

Remove a value from an array using Array.remove[value].

arr_floats = arr.array['f', [2.5, 5.5, 3.0]]
arr_floats.remove[2.5]
print[arr_floats]
### Results
array['f', [5.5, 3.0]]

Similar to the list and tuple, you can also get the length using len[Array], and Maximum and minimum values using max[Array] and min[Array] respectively. Array.count[value] displays the number of times of a value occurs in the array.

Dictionaries

A dictionary is an unordered collection of key-value pairs enclosed by curly braces {}. Dictionaries are useful for storing information in pairs of keys and values.

Unordered means that they cannot be indexed. Key-value pairs means each element has a key which stores the value, and you can access an elements value by its key.

We refer to a key-value pair as an item. A key represents the name of the value, and the value is any python object you need to store such as lists, functions, integers and so on. You can create a python dictionary using Dict={key: value}

dict_2 = {'fruits': ['apple','grape'],
10: 'number of fruits',
'carrier': 'bag'}
print[dict_2]
### Results
{'fruits': ['apple', 'grape'], 10: 'number of fruits', 'carrier': 'bag'}

You can access values by their keys using Dict[key]

print[dict_2['fruits']]
print[dict_2[10]]
### Results
['apple', 'grape']
number of fruits

You can update the values of a key using Dict[existing_key]=new_value

dict_2['carrier'] = 'basket'
dict_2['fruits'].append['banana']
print[dict_2]
### Results
{'fruits': ['apple', 'grape', 'banana'], 10: 'number of fruits', 'carrier': 'basket'}

You can create a new element with its own key-value pair, by using a key that does not exist in the current dictionary. Use Dict[new_key]=new_value

dict_2['status'] = 'not enough'
print[dict_2]
### Results
{'fruits': ['apple', 'grape', 'banana'], 10: 'number of fruits', 'carrier': 'basket', 'status': 'not enough'}

Dictionaries have some convenient functions for accessing either the keys, the values or all the items. These are useful when iterating through the dictionary. You can access the keys using Dict.keys[].

dict_2.keys[]### Results
dict_keys[['fruits', 10, 'carrier', 'status']]

Accessing the values using Dict.values[]

dict_2.values[]### Results
dict_values[[['apple', 'grape', 'banana'], 'number of fruits', 'basket', 'not enough']]

Accessing the items using Dict.items[]

dict_2.items[]### Results
dict_items[[['fruits', ['apple', 'grape', 'banana']], [10, 'number of fruits'], ['carrier', 'basket'], ['status', 'not enough']]]

Sets

We cannot talk about python data structures without mentioning Sets, which we will not get into much details in this article.

Sets are unordered collections of unique objects enclosed by curly braces{} not to be confused with dictionaries which are also enclosed with curly braces.

Unordered means the elements are not ordered therefore cannot be indexed. Unique means that a set cannot store duplicate values and are therefore very handy for removing duplicates from lists. You can store any python objects in a set. A set is created using Set={values}. You can convert a list into a set using Set[list].

Sets have their own unique operations for merging two sets. These are union[] function or | operator, intersection[] function or & operator, and the difference[] function or operator.

Thats it for now. This was a reference starter guide for using lists, tuples and dictionaries. There is so much more you can do with these data structures and I encourage you to practice and experiment as much as you can using the extensive information online. Best of luck!

Video liên quan

Chủ Đề