DEV Community

Cover image for Mastering Python Lists
Eric The Coder
Eric The Coder

Posted on

2 2

Mastering Python Lists

Hi, here are common Pyton List Manipulation methods.

If you like this post and want more follow me on Twitter: Follow @justericchapman

In Python, List are a collection of items is particular order. You can put anything you want into a List.

By convention normally you will make the name your List plural. For example a list of person can be name people.

Python use square bracket [] to indicate a List, and individual elements are separated by commas.

List is zero base. That mean the first position is 0 and the second position is 1, etc.

# Create a list
fruits = ['orange', 'apple', 'melon']

# Accessing a List element
fruits[0]  # first item
fruits[-1] # last item

# Append to List
fruits.append('banana')

# Insert to List at position x
fruits.insert(1, 'banana') # will be insert second in the List

# List length
nb_items = len(fruits) # 4

# Remove from list
del fruits[1]   # remove apple

# Remove and return last element
lastFruit =  fruits.pop()   # remove last and return it's value into lastFruit

# Slice my_list[start:finish:step] ([::-1] reverse list) 
fruits = fruits[1:3]
fruits[:3]  # first 3
fruits[2:]  # last 2
copy_fruits = fruits[:] # copy 

#Create list from string
colors = 'red, green, blue'.split(', ')

#Reverse a List
colors.reverse()

# Array concact
color1 = ['red', 'blue']
color2 = ['green', 'yellow']
color3 = color1 + color2

# Concat by unpacking
color3 = [*color1, *color2]

# Multiple assignment
name, price = ['iPhone', 599]

#Create a Tuple (kind of read only list)
colors = ('red', 'green', 'blue')

# Sort
colors.sort() # ['blue', 'green', 'red']
colors.sort(reverse=True) # ['red', 'green', 'blue']
colors.sort(key=lambda color: len(color)) # ['red', 'blue', 'green']

# Looping in a List
for color in colors:
  print(color)

# Generate a List of numbers
numbers = List(range(1, 10)) # 1 2 3 4 5 6 7 8 9

# List comprehension offers a shorter syntax when you want 
# to create a new list based on the values of an existing list.

# Example of long version
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newFruits = []

for x in fruits:
  if "a" in x:
    newFruits.append(x)

print(newFruits)

# Same example with List Comprehension 
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newFruits = [x for x in fruits if "a" in x]
# Syntax:   [expression for item in iterable if condition == True]

print(newFruits)
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay