Dylan North

Dylan North

1570679168

Python List Functions | Tutorial for Beginners.

This is image title
A Python list is a sequence of values. It can consist of any types, strings, numbers, floats, mixed content, whatever. In this post, we will talk about Python list functions and how to create elements, add elements, append elements, reverse elements, and perform many other Python list functions.

Create Python Lists

There are several ways to create a Python list. The easiest way is to enclose your elements in square brackets like this: mylist = [10, 20, 30, 40, 50].

You can make a list of strings like this: mylist = [‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’].

The elements of a list don’t have to be the same type. You can mix them like this:* mylist = [‘first’, 20, 5.5, [10, 15], ‘fifth’].*

You can write nested lists, which means lists inside lists live the above example. Also, you can access any element of the list by its index, which is zero-based: thirdelem = mylist[2].

List indices work the same way as string indices. You can review my Python programming basics post for more info.

Mutable Lists

Unlike strings, lists are mutable because you can change the order of items in a list or reassign an item in a list.

If we have a list like mylist = [‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’], we can change the third item like this: mylist[2] = “New item”.

Now, if you print the list, you should see the new list: [‘first’, ‘second’, ‘New item’, ‘fourth’, ‘fifth’].

If you try to read or write an element that does not exist, you get an IndexError.

Like strings, if an index has a negative value, it counts backward from the end of the list.

mylist = ['first', 'second', 'third', 'fourth', 'fifth']
elem = mylist[-1]
print(elem)

The output of this code will be fifth.

Traverse a List

You can traverse the elements of a list using a for loop like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']
for elem in mylist:
    print(elem)

This works well if you need to read the elements of the list. But if you want to update the elements, you need the indices like this:

mylist = [1, 2, 3, 4, 5]
for i in range(len(mylist)):
    mylist[i]+=5
print(mylist)

The result will be* [6, 7, 8, 9, 10]*.

len() returns the number of elements in the list, while range() returns the list of indices.

Keep in mind that the nested list still counts as a single element, regardless of how many elements are inside it.

mylist = ['first', 20 , 5.5 , [10, 15], 'fifth']
print(len(mylist))

The result of the above code is 5.

Slice a List

The slice operator also works on lists like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']
print(mylist[1:3])

The result from the above code will be* [‘second’, ‘third’] *.

If you omit the first index, the slice starts from the beginning. If you omit the second, the slice goes to the end.

If you omit both, the slice is a copy of the whole list.

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

print(mylist[1:3])

print(mylist[1:])

print(mylist[:3])

print(mylist[:])

The result of the above code will be:

['second', 'third']

['second', 'third', 'fourth', 'fifth']

['first', 'second', 'third']

['first', 'second', 'third', 'fourth', 'fifth']

Since lists are mutable, you can change elements using the slice operator:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

mylist[1:3] = ['Hello', 'Guys']

print(mylist)

The result will be [‘first’, ‘Hello’, ‘Guys’, ‘fourth’, ‘fifth’].

Insert Into a List

You can insert a new element to the list using the insert method like this:

mylist = [1, 2, 3, 4, 5]

mylist.insert(1,'Hello')

print(mylist)

The result will be* [1, ‘Hello’, 2, 3, 4, 5].*

Also, the index of the inserted element is zero-based.

Append to a List

You can add a new element to the end of a list using the append method like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

mylist.append("new one")

print(mylist

The result will be* [‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’, ‘new one’].*

You can append more than one element using the extend method like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

list2 = ["Hello", "Guys"]

mylist.extend(list2)

print(mylist)

The result will be [‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’, ‘Hello’, ‘Guys’].

Of course, list2 will remain untouched.

Sort a List

The sort method sorts the elements of the list from low to high.

mylist = ['cde', 'fgh', 'abc', 'klm', 'opq']

list2 = [3, 5, 2, 4, 1]

mylist.sort()

list2.sort()

print(mylist)

print(list2)

The output will be:

['abc', 'cde', 'fgh', 'klm', 'opq']

[1, 2, 3, 4, 5]

Reverse a List

You can reverse the order of a python list using the reverse method like this:

mylist = [1, 2, 3, 4, 5]

mylist.reverse()

print(mylist)

The output will be* [5, 4, 3, 2, 1].*

Index of an Element

You can get the index of an element using the index method like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

print(mylist.index('second'))

The result will be 1.

If you have more than one element with the same name supplied to the index function, it will return the first index that matches the supplied value.

This is image title

Delete an Element

There are several ways to delete elements from a list. If you know the index of the element you want to delete, you can use the pop method like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

removed = mylist.pop(2)

print(mylist)

print(removed)

The result will be:

['first', 'second', 'fourth', 'fifth']

third

If you don’t specify an index for the pop method, it will delete the last element.

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

removed = mylist.pop()

print(mylist)

print(removed)

The result will be:

['first', 'second', 'third', 'fourth']

fifth

If you don’t know the index of the element, but you know the element itself, you can remove it using like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

mylist.remove('second')

print(mylist)

The result will be [‘first’, ‘third’, ‘fourth’, ‘fifth’].

If you don’t need the removed value, you can use the del operator like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

del mylist[2]

print(mylist)

The result will be [‘first’, ‘second’, ‘fourth’, ‘fifth’].

Also, you can delete multiple elements using the slice operator like this: The result will be [‘first’, ‘fourth’, ‘fifth’].

Aggregate Functions

There are a number of built-in aggregate functions that can be used on lists that allow you to go through the list without writing a loop.

mylist = [5, 3, 2, 4, 1]

print(len(mylist))

print(min(mylist))

print(max(mylist))

print(sum(mylist))

The sum() function only works when the list elements are numbers.

The other functions (max(), len(), etc.) work with lists of strings and other types that can be comparable.

Compare Lists

If you are using Python 2, you can compare elements of two lists using the cmp function like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

list2 = ['fourth', 'first', 'second', 'fifth', 'third']

print(cmp(mylist,list2))

It will return -1 if there’s no match and 1 if it matches.

If you are using Python 3, you can compare two lists using the == operator like this:

mylist = ['first', 'second', 'third', 'fourth', 'fifth']

list2 = ['fourth', 'first', 'second', 'fifth', 'third']

if (mylist == list2):

    print("match")

else:

    print("No match")

The result will be No match.

List Operations

The + operator concatenates lists like this:

list1 = [1, 2, 3]

list2 = [4, 5, 6]

print(list1 + list2)

The output will be 1, 2, 3, 4, 5, 6].

Also, you can repeat a list using the multiply operator like this:

list1 = [1, 2, 3]

list2 = [4, 5, 6]

print(list1 * 2)

The result will be* [1, 2, 3, 1, 2, 3].*

Lists and Strings

A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string.

To convert a string to a list of characters, you can use the list function like this:

mystr = "LikeGeeks"

mylist = list(mystr)

print(mylist)

The result will be [‘L’, ‘i’, ‘k’, ‘e’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’].

The list function breaks a string into individual letters as shown.

If you want to break a string into words, you can use the split method instead:

mystr = "Welcome to likegeeks website"

mylist = mystr.split()

print(mylist)

The result will be [‘Welcome’, ‘to’, ‘likegeeks’, ‘website’].

As you can see, the returned output is a normal list; you can get any word by index and manipulate it.

Also, you can specify a delimiter for the split method. So, instead of the default delimiter (which is the space), you can supply another one.

Join a List

The opposite process of splitting a string to a list of strings is to join them to make a string.

You can concatenate a list of strings to make a string using the join method like this:

mylist = ['Welcome', 'to', 'likegeeks', 'website']

delimiter = ' '

output = delimiter.join(mylist)

print(output)

The output will be Welcome to likegeeks website.

Aliasing

When two variables referencing the same object like below, an object with more than one reference has more than one name. So, we say that the object is aliased.

mylist = ['Welcome', 'to', 'likegeeks', 'website']

list2 = mylist

Since Python lists are mutable, changes made with one alias affect the other:

mylist = ['Welcome', 'to', 'likegeeks', 'website']

list2 = mylist

list2[3] = "page"

print(mylist)

The result will be [‘Welcome’, ‘to’, ‘likegeeks’, ‘page’].

We made a change to list2, but since they are referencing to the same object and that object is mutable, the changes affect the original list.

It is safer to avoid aliasing when you are working with mutable objects like lists.

It can be useful, but it can also be a source of errors — so be careful when working with mutable objects when they are aliased.

Working with a Python list is very easy, as we’ve seen. I hope you find the post useful and interesting. Keep coming back!

Let’s share it!

Learn More

This is image title

#python

What is GEEK

Buddha Community

Python List Functions | Tutorial for Beginners.

Great

Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Sival Alethea

Sival Alethea

1624291780

Learn Python - Full Course for Beginners [Tutorial]

This course will give you a full introduction into all of the core concepts in python. Follow along with the videos and you’ll be a python programmer in no time!
⭐️ Contents ⭐
⌨️ (0:00) Introduction
⌨️ (1:45) Installing Python & PyCharm
⌨️ (6:40) Setup & Hello World
⌨️ (10:23) Drawing a Shape
⌨️ (15:06) Variables & Data Types
⌨️ (27:03) Working With Strings
⌨️ (38:18) Working With Numbers
⌨️ (48:26) Getting Input From Users
⌨️ (52:37) Building a Basic Calculator
⌨️ (58:27) Mad Libs Game
⌨️ (1:03:10) Lists
⌨️ (1:10:44) List Functions
⌨️ (1:18:57) Tuples
⌨️ (1:24:15) Functions
⌨️ (1:34:11) Return Statement
⌨️ (1:40:06) If Statements
⌨️ (1:54:07) If Statements & Comparisons
⌨️ (2:00:37) Building a better Calculator
⌨️ (2:07:17) Dictionaries
⌨️ (2:14:13) While Loop
⌨️ (2:20:21) Building a Guessing Game
⌨️ (2:32:44) For Loops
⌨️ (2:41:20) Exponent Function
⌨️ (2:47:13) 2D Lists & Nested Loops
⌨️ (2:52:41) Building a Translator
⌨️ (3:00:18) Comments
⌨️ (3:04:17) Try / Except
⌨️ (3:12:41) Reading Files
⌨️ (3:21:26) Writing to Files
⌨️ (3:28:13) Modules & Pip
⌨️ (3:43:56) Classes & Objects
⌨️ (3:57:37) Building a Multiple Choice Quiz
⌨️ (4:08:28) Object Functions
⌨️ (4:12:37) Inheritance
⌨️ (4:20:43) Python Interpreter
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=rfscVS0vtbw&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=3

🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#python #learn python #learn python for beginners #learn python - full course for beginners [tutorial] #python programmer #concepts in python

Osiki  Douglas

Osiki Douglas

1624591552

The anatomy of Python Lists

An easy guide to summarize the most common methods and operations regarding list manipulation in Python.

Python lists are a built-in type of data used to store items of any data type such as strings, integers, booleans, or any sort of objects, into a single variable.

Lists are created by enclosing one or multiple arbitrary comma-separated objects between square brackets.

Lists may contain elements of different data types

List items follows a sequenced or specific order

Access values by index

#python-programming #python #tutorial #list-manipulation #python-list #the anatomy of python lists

Kennith  Blick

Kennith Blick

1625749440

Introduction to Lists in Python - Beginner Python Tutorial #6

Get started with Python!
In this Python tutorial, we will start learning about one of the most versatile data types in Python: Lists. In this video you will grasp the most important basic operations on lists.
Lists are very much used in Python and you will get a complete picture after watching the next video where we will learn about list methods.

Lists will be covered in two parts (2 videos):

  • Part 1: BASIC OPERATIONS ON LISTS
  • Part 2: LISTS METHODS

Playlist: Beginner Python Tutorials | Video #6
Access the code here: https://github.com/rscorrea1/youtube.git

Timestamp:
0:00 - Start of the video
0:24 - How to create a list
2:31 - Basic operations on lists
2:33 - How to calculate list length
3:26 - How to retrieve a list element
5:30 - How to reassign the value of any list element
6:48 - Dealing with nested lists
8:26 - How to retrieve slices from a list
10:24 - Lists concatenation
12:00 - Lists repetition
12:35 - Announcement for the next video
12:47 - Github account

Thumbnail:
Photo by Mario Ho on Unsplash

#python #lists in python #beginner python tutorial