Lists, Tuples, Slicing, Sets, and List Comprehensions with Python

2020-08-01 13:14:30 | #programming #python | Part 3 of 7

In this guide, we're focusing on Python lists and their capabilities. We'll start with the basics, with list creation, appending, and retrieving by index. And then move on to more advanced concepts.

With lists, you now have the ability to manage collections of values that can be dynamically populated, sorted, and updated. You also become more efficient at referencing large sets of data with patterns and algorithms.

Python Lists

Lists give us the power to store data/values into a collection, reorder and modify them.

Manually Creating a List with Python

Manual list creation is as easy as definining comma-separated values within square brackets. By storing the list into the variable numbers, we can access its elements by index, starting at 0.

Try It Yourself


 
  

Creating a Python List Dynamically Using Range

When we need to define a range of elements, we pass the starting value and ending value into the range function. The following example also demonstrates how to iterate through each item in the list with a for loop.

Try It Yourself


 
  

Appending to a Python List

The append function allows us to add elements to our list.

Try It Yourself


 
  

Negative Indices with Python

Negative indices allow us to retrieve an element from the end of a list. So if numbers is 10 elements long, numbers[-1] will return the last element of the list. numbers[-2] will return the second to last element of the list.

Try It Yourself


 
  

Extracting a Range of Elements from a Python List with Slice

Try It Yourself


 
  

Reversing a Python List

Here's a neat trick you can use to reverse the items in a list. This even works on a string.

Try It Yourself


 
  

Python Stride

Stride is how many steps to take across a range of elements. So providing a stride of 2 will iterate by 2 instead of 1. Check out the following examples to learn more:

Try It Yourself


 
  

Python Append vs. Extend

extend ends up being the better tool for merging lists together, since append inserts the set of values, which produces a nested list.

Try It Yourself


 
  

Python Pop vs. Remove

Use pop when you want to delete an element by index and remove when you want to delete an element by value. If you don't pass an index to pop, it will delete the element at the end of the list.

Try It Yourself


 
  

Python Tuples

Tuples are very similar to lists, but they're immutable. Once defined, you can't change the values, add to, or remove from a tuple. So what is the advantage of immutability? Immutable objects are inherently simpler and reduce the number of bugs in a program because the state of the object doesn't change and dependencies don't need to account for all the possible states.

Also, while lists have order, tuples have structure. Tuples are often found to store pairs or triplets of data, i.e. XY coordinates or RGB values. Note: you create tuples with parenthesis, rather than square brackets. Check out the examples below.

Try It Yourself


 
  

Knowing that tuples are immutable, what do you think would happen if you tried to append, pop, or index?

Python Tuple vs. Lists

  • Tuples perform better than lists. Always use tuples when working with constant values you just need to iterate over.
  • Tuples require less memory than lists. Because you can append to lists, Python will actually create a larger allocation for lists in memory in case you append.
  • Tuples can be used as dictionary keys because they are immutable, where a list isn't.

Try It Yourself


 
  

Python List Comprehensions

List comprehensions are kind of a shorthand way of writing loops.

Performing Mathematical Operations on Every Element

Try It Yourself


 
  

Filtering Elements with Python

Try It Yourself


 
  

Python Sets

What makes sets different is that they are unordered, and unindexed, and written with a different syntax.

Creating and Retrieving Values from a Python Set

Try It Yourself


 
  

Modifying a Python Set

Try It Yourself


 
  

Python Programming Exercises

Try to solve the following problems, using everything you've learned up to this point. Feel free to share solutions in the comments. Optimize each solution, as much as possible.

  1. Write a Python function that accepts a string and returns True if that string is a palindrome

    Input: 'moon'

    Expected Output: False

    Input: 'noon'

    Expected Output: True

    Input: 'rotator'

    Expected Output: True

    Try It Yourself


     
              
  2. Write a Python list comprehension that filters out the even numbers of a list of integers

    Input: [1, 3, 4, 6, 2, 9, 68, 53]

    Expected Output: [4, 6, 2, 68]

    Try It Yourself


     
              
  3. Write a Python list comprehension that squares all of the integers of a list

    Input: [2, 5, 3, 4, 8]

    Expected Output: [4, 25, 9, 16, 64]

    Try It Yourself


     
              
  4. Write a Python list comprehension that cubes all of the integers of a list

    Input: [2, 5, 3, 4, 8]

    Expected Output: [8, 125, 27, 64, 512]

    Try It Yourself


     
              
  5. Write a Python function that accepts two parameters - a list of integers: numbers and an integer: power. Have the function return a new list of all the integer items raised to power

    Input: [2, 5, 3, 4, 8], 4

    Expected Output: [16, 625, 81, 256, 4096]

    Input: [2, 5, 3, 4, 8], 6

    Expected Output: [64, 15625, 729, 4096, 262144]

    Try It Yourself


     
              

Want To See More Exercises?

View Exercises

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.



Tell Us About Your Project









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Hire Us

We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

Contact