Python Lists, Operations & methods, Differences/similarities between Arrays, Lists or Tuples

5/5 - (1 vote)

!! A list is a collection used to store data, which is ordered and changeable.

A collection allows us to put many values in a single “variable”.

The data could be a mix of any of the datatypes!

In Python, lists are written with square brackets (a list looks like the arrays from Javascript).

As opposed to arrays, the lists do not need declaration in Python, because they are a part of Python’s syntax.

How to create a list?

To create a List use square brackets.

The elements in the list are separated by commas.

friends = ["Mike", "John", "Doe", "Will", "Ted"]
print(friends)

#result ['Mike', 'John', 'Doe', "Will", "Ted"]

friends is a list of strings.

How to initialize a list?

You can initialize a list as:

arr = list()
# or simply
arr = []

A list element can be any Python object, even another list!
random_things = [1, 4.0, ‘hello’, True]

A list can be empty
empty_list = []

Building a list from scratch

Create an empty list then add elements using the append() method.

The list stays in order and new elements are added at the end of the list.

#creating list from scratch
my_list = list()
my_list.append(1)
my_list.append(2)
my_list.append('hello')
print(my_list)
//[1, 2, 'hello']

Access items from a list

You access the list items by referring to the index number:

friends = ["Mike", "John", "Doe"]
print(friends[1])

#result John

We can also index from the end of the lists, using negative indices.

0 for the first element, -1 for the last element

If you attempt to access an index in a list that does not exist, You will get a list index exception.

How to loop through a list?

You can loop through the list items by using a for loop:

friends = ["Mike", "John", "Doe"]

for name in friends:
    print(name)

#Result
Mike
John
Doe

Slice and Dice with Lists

Slicing, means using indices to slice off parts of a list or string.

friends = ["Mike", "John", "Doe", "Will", "Ted"]
print(friends[1:3])
# ['John', 'Doe']

If you would like to make a slice that begins of the original list, You can omit the starting index.

friends = ["Mike", "John", "Doe", "Will", "Ted"]
print(friends[:3])
# ['Mike','John', 'Doe']

Negative indexes work in slices!

The important characteristics of Python list

The important characteristics of Python lists are:

Lists are mutable

We can change an element of a list using the index operator!

numbers = [1,2,3,4,5]
numbers[0] = 9
print(numbers)

//[9, 2, 3, 4, 5]

This one of the most important features for lists.

Once a list has been created, elements can be added, deleted, shifted, or moved.

Everything in Python is an object and all objects in Python can be either mutable or immutable.
If an object can be changed, then it is called mutable. However, if an object cannot be changed with creating a completely new object, then the object is considered immutable.

Strings are immutable! We cannot change the contents of a string!

To make any change we must make a new string! If you try this You get an error: “TypeError: ‘str’ object does not support item assignment”

my_str = 'webpedia'
my_str[1] = 'x'
//
TypeError: 'str' object does not support item assignment

Since everything in Python is an Object, every variable holds an object instance.

A mutable object can be changed after it was created while an immutable object can’t.

Objects of built-in types like (list, set, dictionary) are mutable.

colors = ['red', 'blue', 'white', 'yellow']
colors[0] = 'black'
print(colors)
# ['black', 'blue', 'white', 'yellow']

This is possible because lists are mutable.

colors = ['red', 'blue', 'white', 'yellow']
new_colors = colors
colors[0] = 'green'
print(colors)
print(new_colors)

# ['green', 'blue', 'white', 'yellow']
# ['green', 'blue', 'white', 'yellow']

The change of color variable is reflected in the value of new_color variable, because lists are mutable. This affect both variables: colors and new_colors.
Any of them can be used to access or change the list.

Objects of built-in types like (int, float, bool, strings, tuple) are immutable.

letters = 'abcde'
letters[0] = 'f'
# TypeError: 'str' object does not support item assignment

This is not possible because strings are immutable. This means to change this string, you will need to create a completely new string.

When we create a variable that holds an immutable object, the value of that immutable object is saved in memory.

color = 'blue'
new_color = color
color = 'red'
print(color)
print(new_color)

# red
# blue

The change of color variable is not reflected in the value of new_color variable, because new_color is String, which is immutable.

Lists can contain any arbitrary objects.

List elements can be accessed by index.

Lists Are Ordered.

Order is about whether the position of an element in the object can be used to access the element.

e.g, strings and lists are ordered. We can use the order to access parts of a list and string.

Lists can be nested

Nested lists

Double lists

In Python any table can be represented as a list of lists (a list, where each element is another list).
For example, below is a table with two rows and three columns:

number_grid = [
    [1,2,3],
    [4,5,6],
]
print(number_grid[1][2])

#Result 6

How to loop through a list?

You can loop through the nested list items by using a double for loop:

number_grid = [
    [1,2,3],
    [4,5,6],
]

for row in number_grid:
    for col in row:
        print(col)

Python list operations, methods & functions

Lists are most similar to strings. Both types support the len() function, indexing and slicing.

Concatenating lists

You can create a new list by adding two lists together:

#concatenating lists
l1 = [1,2,3]
l2 = [5,6,7,8]
l3 = l1 + l2
print(l3)
//
[1, 2, 3, 5, 6, 7, 8]

How to Find the Length of List in Python?

The len() function returns how many elements are in a list.
The len of the string is a number of characters, while the length of the list is a number of elements it holds.

colors = ['red', 'blue', 'white', 'yellow']
print(len(colors))
# 4

in OR not in?

Use “in” and “not in” to check if an element exists within a list, or for strings if one string is a substring of another.

colors = ['red', 'blue', 'white', 'yellow']
print('red' in colors)
# True

range() function

The range function returns a list of numbers that range from 0 to one less than the parameter.
We can construct an index loop using for and an integer operator.

for i in range(3):
    print(i)

//0
1
2

We can iterate through a list using range() and a for loop – a counted loop.

for i in range(len(letters)):
    print(letters[i])
//a,b,c,d

or

letters = ['a','b','c','d']
for letter in letters:
    print(letter)
//a,b,c,d

max() function

max() returns the greatest element of the list.
How the greatest element is determined depends on what type of objects are on the list.

The maximum element in a list of numbers is the largest number.

The maximum element in a list of strings is the element that would occur last if the list were sorted alphabetically.

The max element is undefined for lists that contain elements from different types, e.g a list with String and Int elements

min() function

min() returns the smallest element in a list. The min() is the opposite of max.

join() method

Join is a string method that takes a list of strings as an argument and returns a string consisting of the list elements joined by a separator string.

my_str = "\n".join(["a", "b", "c"])
print(my_str)
# a
# b
# c

Join will trigger an error, if You try to join anything other then strings.

split() method

Split a string into a list where each word is a list item, e.g:

text = "welcome to webpedia"
my_list = text.split()
print(my_list)

# ['welcome', 'to', 'webpedia']

append() method

append() adds an element to the end of a list.

letters = ['a', 'b', 'c']
letters.append('d')
print(letters)
# 'a', 'b', 'c', 'd']

extend() method

Merges another list to the end.

insert(i,x) method

Inserts element x at position i.

remove(x) method

Removes the first occurrence of element x.

pop() method

Removes the last element of a list. If an argument is passed, that index item is popped out.

index(x) method

Returns the first index of a value in the list. Throws an error if it’s not found.

count(x) method

Counts the number of occurrences of an element x.

reverse() method

Reverses the list.

How to sort a list?

!! A list can hold many items and keep those items in the order until we change the order.

sort() method

You can sort a list, Ascending or Descending, using the sort() method.

The syntax of the sort() method is:

list.sort(key=…, reverse=…)

numbers = [7,11,3,5,0,33]
numbers.sort(reverse=True)
print(numbers)

#Result [33, 11, 7, 5, 3, 0]

Alternatively, you can also use Python’s in-built function sorted().

sorted() method

sorted() returns a copy of a list in order from smallest to largest, leaving the list unchanged.

sorted(list, key=…, reverse=…)

The difference between sort() and sorted() is: sort() doesn’t return any value while, while sorted() returns an iterable list, leaving the initial list unchanged.

How to sum a list of numbers in Python?

Python provide an inbuilt function sum() which sums up the numbers in the list.

Which are the differences/similarities between Arrays and Lists?

Similarities

  • Both arrays and lists can be used to store elements, both are mutable, both can be indexed, sliced and iterated through.

Differences

  • Arrays must be declared, while the lists do not need to be declared.
  • Arrays can only be used for specific types, whereas lists can be used for any object.
  • The mostly difference between the lists and arrays are the functions you can perform on them.

When it is better to use lists and when to use arrays?

Even if in Python lists are more often used than arrays, there are cases when sometimes it is good to use lists and sometimes to use arrays.

  • If you want to do numerical operations on your data, your best choice is arrays, Because, if you try to do mathematical operations on individual elements of a list you will get an error:
  • A list is an efficient way of storing data because You can create a list of anything, with any data type; but if you want to store a large amount of data, use arrays because they can store data very efficiently
  • Lists use more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go.
  • It’s faster to access individual list items in arrays: O(1) versus O(n)

Which are the differences/similarities between Lists and Tuples?

Tuples in Python are used to collect an immutable ordered list of elements, therefore:

  • You can’t add elements to a tuple. Tuples don’t have append() or extend() methods.
  • You can’t remove elements from a tuple. Tuples don’t have remove() or pop() methods.

but You can still:

  • find elements, since this doesn’t change the elements.
  • use the “in” operator to check if an element exists in the tuple.

Also are cases when its better use tuples instead of lists, like:

  • Tuple’s size is fixed, so it can be stored more compactly than lists which need to over-allocate to make append() operations efficient.
  • Tuples refer directly to their elements, therefore this gives tuples a speed advantage for indexed lookups.
  • If you’re defining a constant set of values and all you need is to iterate through it, use a tuple instead of a list. It will be faster than working with a list.

List Comprehensions

List comprehensions creates a dynamic list, a short and powerful way to create lists in Python without having to use different for loops to append values one by one.

List comprehensions are one of Python’s unique features. List comprehensions in Python are constructed as follows:

list_variable = [x for x in iterable]

Conditionals in List Comprehension

List comprehensions can utilize conditional statement to modify an existing list

list_variable = [x for x in iterable if condition]

List comprehensions examples

Creates squares of a set of numbers

With a list comprehensions

squares = [n**2 for n in range(5)]
print(squares)

#[0, 1, 4, 9, 16]

Without a list comprehension:

squares = [n**2 for n in range(10) if n%2 == 0]

#[0, 1, 4, 9, 16]

Creates squares of an even set of numbers

squares = [n**2 for n in range(10) if n%2 == 0]
print(squares)

Make a list of reversed tuples gettig from a dictionary and then sort it.

colors = {‘red’: 2, ‘blue’: 3, ‘green’: 1, ‘white’: 1, ‘black’: 1}
print(sorted( [ (v, k) for k,v in colors.items()] ))
[(1, ‘black’), (1, ‘green’), (1, ‘white’), (2, ‘red’), (3, ‘blue’)]

Hackerrank List Comprehensions problem

Hackerrank List Comprehensions problem:

X,Y,Z and representing the dimensions of a cuboid along with an integer N. You have to print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum i+j+k is not equal to N.

Solving using list comprehension

x = int(input())
y = int(input())
z = int(input())
n = int(input())

list = [[i, j, k]
    for i in range(x + 1)
    for j in range(y + 1)
    for k in range(z + 1)
    if i+j+k !=n]

print(list)

#Resut
2
2
2
2
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 2], [0, 2, 1], [0, 2, 2], [1, 0, 0], [1, 0, 2], [1, 1, 1], [1, 1, 2], [1, 2, 0], [1, 2, 1], [1, 2, 2], [2, 0, 1], [2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0], [2, 2, 1], [2, 2, 2]]

Return the number of negative numbers in a given list

def count_negatives(nums):
    return len([num for num in nums if num < 0])

Conclusions about Lists in Python

  • Lists are mutable.
  • Lists are ordered
  • List items are always indexed with numbers starting at 0
  • List are sortable.

List Exercises

Read a file and build a list of unique words

Open the file and read it line by line.
Then build a list of unique words. In the end, prints the resulting words in alphabetical order.

fname = input("Enter a file name: ")
try:
    fh = open(fname)
except:
    print("Can't open the file:",fname)
    quit()
lst = list()
for line in fh:
    line = line.rstrip()
    words = line.split()
    for word in words:
        if word not in lst:
            lst.append(word)

lst.sort()
print(lst)

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

subscribe youtube

Leave a Comment

WebPedia.net