Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 29, 2021 11:45 am GMT

Mastering Python Lists

Hi, here are common Pyton List Manipulation methods.

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

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 listfruits = ['orange', 'apple', 'melon']# Accessing a List elementfruits[0]  # first itemfruits[-1] # last item# Append to Listfruits.append('banana')# Insert to List at position xfruits.insert(1, 'banana') # will be insert second in the List# List lengthnb_items = len(fruits) # 4# Remove from listdel fruits[1]   # remove apple# Remove and return last elementlastFruit =  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 3fruits[2:]  # last 2copy_fruits = fruits[:] # copy #Create list from stringcolors = 'red, green, blue'.split(', ')#Reverse a Listcolors.reverse()# Array concactcolor1 = ['red', 'blue']color2 = ['green', 'yellow']color3 = color1 + color2# Concat by unpackingcolor3 = [*color1, *color2]# Multiple assignmentname, price = ['iPhone', 599]#Create a Tuple (kind of read only list)colors = ('red', 'green', 'blue')# Sortcolors.sort() # ['blue', 'green', 'red']colors.sort(reverse=True) # ['red', 'green', 'blue']colors.sort(key=lambda color: len(color)) # ['red', 'blue', 'green']# Looping in a Listfor color in colors:  print(color)# Generate a List of numbersnumbers = 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 versionfruits = ["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)

Original Link: https://dev.to/ericchapman/python-list-414e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To